本文整理汇总了Python中trac.util.datefmt.to_datetime函数的典型用法代码示例。如果您正苦于以下问题:Python to_datetime函数的具体用法?Python to_datetime怎么用?Python to_datetime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_datetime函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: get_search_results
def get_search_results(self, req, keywords, filters):
self.log.debug("PHPDOCBUG: kw=%s f=%s" % (keywords, filters))
if not 'phpdoc' in filters:
return
# We have to search for the raw bytes...
keywords = [k.encode(self.encoding) for k in keywords]
for doc in os.listdir(self.base_path):
# Search in documentation directories
path = os.path.join(self.base_path, doc)
path = os.path.join(path, self.html_output)
self.log.debug("looking in doc (%s) dir: %s:" % (doc, path))
if os.path.isdir(path):
index = os.path.join(path, 'search.idx')
if os.path.exists(index):
creation = os.path.getctime(index)
for result in self._search_in_documentation(doc, keywords):
result['url'] = req.href.phpdoc(doc) + '/' \
+ result['url']
yield result['url'], result['name'], to_datetime(creation), \
'phpdoc', None
# Search in common documentation directory
index = os.path.join(self.base_path, self.html_output)
index = os.path.join(index, 'search.idx')
self.log.debug("looking in doc (%s) search.idx: %s:" % (doc, index))
if os.path.exists(index):
creation = os.path.getctime(index)
for result in self._search_in_documentation('', keywords):
result['url'] = req.href.phpdoc() + '/' + \
result['url']
yield result['url'], result['name'], to_datetime(creation), 'phpdoc', \
None
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:34,代码来源:phpdoctrac.py
示例2: expand_macro
def expand_macro(self, formatter, name, content):
env = formatter.env
req = formatter.req
if not 'VOTE_VIEW' in req.perm:
return
# Simplify function calls.
format_author = partial(Chrome(self.env).format_author, req)
if not content:
args = []
compact = None
kw = {}
top = 5
else:
args, kw = parse_args(content)
compact = 'compact' in args and True
top = as_int(kw.get('top'), 5, min=0)
if name == 'LastVoted':
lst = tag.ul()
for i in self.get_votes(req, top=top):
resource = Resource(i[0], i[1])
# Anotate who and when.
voted = ('by %s at %s'
% (format_author(i[3]),
format_datetime(to_datetime(i[4]))))
lst(tag.li(tag.a(
get_resource_description(env, resource, compact and
'compact' or 'default'),
href=get_resource_url(env, resource, formatter.href),
title=(compact and '%+i %s' % (i[2], voted) or None)),
(not compact and Markup(' %s %s' % (tag.b('%+i' % i[2]),
voted)) or '')))
return lst
elif name == 'TopVoted':
realm = kw.get('realm')
lst = tag.ul()
for i in self.get_top_voted(req, realm=realm, top=top):
if 'up-only' in args and i[2] < 1:
break
resource = Resource(i[0], i[1])
lst(tag.li(tag.a(
get_resource_description(env, resource, compact and
'compact' or 'default'),
href=get_resource_url(env, resource, formatter.href),
title=(compact and '%+i' % i[2] or None)),
(not compact and ' (%+i)' % i[2] or '')))
return lst
elif name == 'VoteList':
lst = tag.ul()
resource = resource_from_path(env, req.path_info)
for i in self.get_votes(req, resource, top=top):
vote = ('at %s' % format_datetime(to_datetime(i[4])))
lst(tag.li(
compact and format_author(i[3]) or
Markup(u'%s by %s %s' % (tag.b('%+i' % i[2]),
tag(format_author(i[3])), vote)),
title=(compact and '%+i %s' % (i[2], vote) or None)))
return lst
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:60,代码来源:__init__.py
示例3: _parse_build
def _parse_build(self, res):
data = json.loads(res.read())
if not 'results' in data or not (type(data['results']) == int):
status = "running"
else:
status = "successful" if data['results'] == 0 else "failed"
build = dict({
'builder': data['builderName'],
'status': status,
'start' : to_datetime(int(data['times'][0]), utc),
'num': data['number'],
})
if len(data['times']) > 1 and type(data['times'][1]) == float:
build['finish'] = to_datetime(int(data['times'][1]), utc)
for prop in data['properties']:
if prop[0] == 'got_revision' and prop[1] != "":
build["rev"] = prop[1]
break
if status == "failed":
build['error'] = ', '.join(data['text'])
try:
for step in data['steps']:
if "results" in step and step["results"][0] == 2:
build['error_log'] = step['logs'][0][1]
break
except (IndexError, KeyError):
pass
return build
开发者ID:Tramort,项目名称:tracbuildbot,代码行数:34,代码来源:buildbot_api.py
示例4: _process_add
def _process_add(self, req, ticket):
if req.method == "POST" and self._validate_add(req):
if req.args.get('reminder_type') == 'interval':
time = clear_time(to_datetime(None))
delta = _time_intervals[req.args.get('unit')](req.args.get('interval'))
time += delta
time = to_utimestamp(time)
else:
time = to_utimestamp(parse_date(req.args.get('date')))
origin = to_utimestamp(to_datetime(None))
self.env.db_transaction("""
INSERT INTO ticketreminder
(ticket, time, author, origin, reminded, description)
VALUES (%s, %s, %s, %s, 0, %s)
""", (ticket.id, time, get_reporter_id(req, 'author'),
origin, req.args.get('description')))
add_notice(req, "Reminder has been added.")
req.redirect(get_resource_url(self.env, ticket.resource, req.href) + "#reminders")
add_script(req, 'ticketreminder/js/ticketreminder.js')
data = {
'ticket': ticket,
'date_hint': get_date_format_hint(),
}
return ("ticket_reminder_add.html", data, None)
开发者ID:trac-hacks,项目名称:trac-ticketreminder,代码行数:29,代码来源:api.py
示例5: _fetch_fields
def _fetch_fields(self, version=0):
""" Returns a dict with field/value combinations for the content
of a specific version of a blog post, or last/current version if
version is 0.
Returns emtpy dict if no such post or post/version exists. """
self.versions = self.get_versions()
if not self.versions or (version and not version in self.versions):
# No blog post with the name exists
return {}
version = version or self.versions[-1]
cnx = self.env.get_db_cnx()
cursor = cnx.cursor()
cursor.execute("SELECT title, body, publish_time, version_time, "
"version_comment, version_author, author, categories "
"FROM fullblog_posts "
"WHERE name=%s AND version=%s",
(self.name, version) )
fields = {}
for row in cursor:
fields['version'] = version
fields['title'] = row[0]
fields['body'] = row[1]
fields['publish_time'] = to_datetime(row[2], utc)
fields['version_time'] = to_datetime(row[3], utc)
fields['version_comment'] = row[4]
fields['version_author'] = row[5]
fields['author'] = row[6]
fields['categories'] = row[7]
fields['category_list'] = set(_parse_categories(row[7]))
return fields
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:30,代码来源:model.py
示例6: test_to_datetime_microsecond_negative_timestamps
def test_to_datetime_microsecond_negative_timestamps(self):
# Work around issue1646728 in Python 2.4
expected = datetime.datetime.fromtimestamp(-2345, datefmt.localtz) - datetime.timedelta(seconds=0.678912)
self.assertEqual(datefmt.to_datetime(-2345678912).microsecond, 321088) # 1000000 - 678912
self.assertEqual(datefmt.to_datetime(-2345678912), expected)
self.assertEqual(datefmt.to_datetime(-2345678912L), expected)
self.assertEqual(datefmt.to_datetime(-2345678912.0), expected)
开发者ID:moreati,项目名称:trac-gitsvn,代码行数:8,代码来源:datefmt.py
示例7: 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
示例8: format_date
def format_date(self,content,propname,d,force_date=False,tzinfo=None):
if type(d) == datetime.datetime and force_date == False:
tz = tzinfo or localtz
t = to_datetime(d, tzinfo).astimezone(tz)
content.write("%s:%s\r\n" % (propname,t.strftime("%Y%m%dT%H%M%S")))
elif type(d) == datetime.datetime and force_date == True:
tz = tzinfo or localtz
t = to_datetime(d, tzinfo).astimezone(tz)
content.write("%s;VALUE=DATE:%s\r\n" % (propname,t.strftime("%Y%m%d")))
else:
content.write("%s;VALUE=DATE:%s\r\n" % (propname,d.strftime("%Y%m%d")))
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:11,代码来源:icalview.py
示例9: better_parse_date
def better_parse_date(text, tzinfo=None):
tzinfo = tzinfo or localtz
if text == "now": # TODO: today, yesterday, etc.
return datetime.now(utc)
tm = None
text = text.strip()
# normalize ISO time
match = datefmt._ISO_8601_RE.match(text)
if match:
try:
g = match.groups()
years = g[0]
months = g[1] or "01"
days = g[2] or "01"
hours, minutes, seconds = [x or "00" for x in g[3:6]]
z, tzsign, tzhours, tzminutes = g[6:10]
if z:
tz = timedelta(hours=int(tzhours or "0"), minutes=int(tzminutes or "0")).seconds / 60
if tz == 0:
tzinfo = utc
else:
tzinfo = datefmt.FixedOffset(tzsign == "-" and -tz or tz, "%s%s:%s" % (tzsign, tzhours, tzminutes))
tm = strptime("%s " * 6 % (years, months, days, hours, minutes, seconds), "%Y %m %d %H %M %S ")
except ValueError:
pass
else:
for format in ["%x %X", "%x, %X", "%X %x", "%X, %x", "%x", "%c", "%b %d, %Y"]:
try:
tm = strptime(text, format)
break
except ValueError:
continue
if tm == None:
hint = datefmt.get_date_format_hint()
raise TracError(
'"%s" is an invalid date, or the date format ' 'is not known. Try "%s" instead.' % (text, hint),
"Invalid Date",
)
if not hasattr(tzinfo, "localize"):
# This is a tzinfo define by trac which don't have to deal with dst
dt = datetime(*(tm[0:6] + (0, tzinfo)))
else:
# We need to detect daylight saving correctly - see #...
dt = tzinfo.localize(datetime(*tm[0:6]))
# Make sure we can convert it to a timestamp and back - fromtimestamp()
# may raise ValueError if larger than platform C localtime() or gmtime()
try:
datefmt.to_datetime(datefmt.to_timestamp(dt), tzinfo)
except ValueError:
raise TracError(
'The date "%s" is outside valid range. ' "Try a date closer to present time." % (text,), "Invalid Date"
)
return dt
开发者ID:nagyist,项目名称:agilo,代码行数:53,代码来源:days_time.py
示例10: set_status_dt
def set_status_dt(env,ticket_id,new_status=None,new_time=None,db=None):
order_lst = env.config.getlist('querychart', 'order')
order =[]
custom_fields = {}
for m in order_lst:
ms = m.split(':')
if len(ms) >= 2:
order.append(ms[0])
custom_fields[ms[0]] = ':'.join(ms[1:])
else:
order.append(m)
if not db:
db = env.get_db_cnx()
cursor = db.cursor()
cursor.execute("SELECT newvalue,time,ticket ,field from ticket_change where ticket=%s"
" and field=%s"
" order by time",(ticket_id,'status'))
history=[(row[0],to_datetime(row[1])) for row in cursor]
if new_status:
history.append((new_status,new_time))
result ={}
for new_status,time in history:
#set date by priority of 'order'
#if status date (higher priority than next status) is none, set date to higher priority.
#and set none to lower priority status date.
if not new_status in order:
continue
idx = order.index(new_status)
formated_date = format_date(to_datetime(time))
for m_idx in range(len(order)-1, -1, -1):
if not order[m_idx] in custom_fields:
continue
m_field = custom_fields[order[m_idx]]
if not m_field in result:
result[m_field] = None
if idx==m_idx:
result[m_field]=formated_date
elif idx<m_idx:
result[m_field]=None
else:
if result[m_field]==None:
result[m_field]=formated_date
else:
formated_date=result[m_field]
return result
开发者ID:okamototk,项目名称:kanonconductor,代码行数:52,代码来源:model.py
示例11: format_cell
def format_cell(self, name, value):
value_type = self.determine_type(name)
if value_type == 'time':
return to_datetime(value).strftime('%Y-%m-%d')
if value_type == 'date':
return str(to_datetime(value));
if type(value) == StringType:
return str(value)
if type(value) == UnicodeType:
return value.encode('ascii', 'xmlcharrefreplace')
else:
return value
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:13,代码来源:macro.py
示例12: get_timeline_events
def get_timeline_events(self, req, start, stop, filters, pid, syllabus_id):
if pid is None:
return
is_multi = isinstance(pid, (list, tuple))
if is_multi:
# TODO:
return
# Worklog changes
show_starts = 'workstart' in filters
show_stops = 'workstop' in filters
if show_starts or show_stops:
add_stylesheet(req, "worklog/worklogplugin.css")
ts_start = to_timestamp(start)
ts_stop = to_timestamp(stop)
ticket_realm = Resource('ticket')
db = self.env.get_read_db()
cursor = db.cursor()
cursor.execute("""
SELECT wl.worker,wl.ticket,wl.time,wl.starttime,wl.comment,wl.kind,t.summary,t.status,t.resolution,t.type
FROM (
SELECT worker, ticket, starttime AS time, starttime, comment, 'start' AS kind
FROM work_log
UNION
SELECT worker, ticket, endtime AS time, starttime, comment, 'stop' AS kind
FROM work_log
) AS wl
JOIN ticket t ON t.id = wl.ticket AND project_id=%s AND wl.time>=%s AND wl.time<=%s
ORDER BY wl.time""", (pid, ts_start, ts_stop))
for worker,tid,ts,ts_start,comment,kind,summary,status,resolution,type in cursor:
ticket = ticket_realm(id=tid)
time = to_datetime(ts)
started = None
if kind == 'start':
if not show_starts:
continue
yield ('workstart', pid, time, worker, (ticket,summary,status,resolution,type, started, ""))
else:
if not show_stops:
continue
started = to_datetime(ts_start)
if comment:
comment = "(Time spent: %s)\n\n%s" % (pretty_timedelta(started, time), comment)
else:
comment = '(Time spent: %s)' % pretty_timedelta(started, time)
yield ('workstop', pid, time, worker, (ticket,summary,status,resolution,type, started, comment))
开发者ID:lexqt,项目名称:EduTracTicketWorklog,代码行数:50,代码来源:timeline_hook.py
示例13: extend
def extend(self):
'''
Check for all Changetimes and Return the highest Changetime as
Int
'''
timemax = to_datetime( 0, utc )
timenow = to_datetime( datetime.datetime.now(utc) )
for k in self.__ts:
v = self.__ts[ k ]
ticketdt = to_datetime( v.getfielddef( 'changetime', timenow ) )
if ticketdt > timemax:
timemax = ticketdt
if timemax == timenow:
break
return timemax
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:15,代码来源:pptickets.py
示例14: _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
示例15: get_timeline_events
def get_timeline_events(self, req, start, stop, filters):
self.log.debug("start: %s, stop: %s, filters: %s" % (start, stop,
filters))
if ('discussion' in filters) and 'DISCUSSION_VIEW' in req.perm:
# Create request context.
context = Context.from_request(req)
context.realm = 'discussion-core'
# Get database access.
db = self.env.get_db_cnx()
context.cursor = db.cursor()
# Get API component.
api = self.env[DiscussionApi]
# Add CSS styles and scripts.
add_stylesheet(context.req, 'discussion/css/discussion.css')
# Get forum events.
for forum in api.get_changed_forums(context, start, stop):
# Return event.
title = 'New forum %s created' % (forum['name'],)
description = tag(format_to_oneliner(self.env, context,
forum['subject']), ' - ', format_to_oneliner(self.env,
context, forum['description']))
ids = ('forum', forum['id'])
yield ('discussion unsolved', to_datetime(forum['time'], utc),
forum['author'], (title, description, ids))
# Get topic events.
for topic in api.get_changed_topics(context, start, stop):
title = 'New topic on %s created' % (topic['forum_name'],)
description = format_to_oneliner(self.env, context,
topic['subject'])
ids = ('topic', topic['id'])
yield ('discussion solved' if 'solved' in topic['status']
else 'discussion unsolved', to_datetime(topic['time'], utc),
topic['author'], (title, description, ids))
# Get message events.
for message in api.get_changed_messages(context, start, stop):
title = 'New reply on %s created' % (message['forum_name'],)
description = format_to_oneliner(self.env, context,
message['topic_subject'])
ids = (('topic',message['topic']),'message', message['id'])
yield ('discussion unsolved', to_datetime(message['time'], utc),
message['author'], (title, description, ids))
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:48,代码来源:timeline.py
示例16: get_search_results
def get_search_results(self, req, terms, filters):
if not 'discussion' in filters:
return
# Create context.
context = Context.from_request(req)
context.realm = 'discussion-core'
# Get database access.
db = self.env.get_db_cnx()
cursor = db.cursor()
# Search in topics.
query, args = search_to_sql(db, ['author', 'subject', 'body'], terms)
columns = ('id', 'forum', 'time', 'subject', 'body', 'author')
sql = ("SELECT id, forum, time, subject, body, author "
"FROM topic "
" WHERE %s" % (query,))
self.log.debug(sql)
cursor.execute(sql, args)
for row in cursor:
row = dict(zip(columns, row))
row['time'] = to_datetime(row['time'], utc)
yield (req.href.discussion('topic', row['id']) + '#-1',
"Topic #%d: %s" % (row['id'], shorten_line(row['subject'])),
row['time'], row['author'], shorten_result(row['body'], [query]))
# Search in messages
query, args = search_to_sql(db, ['m.author', 'm.body',
't.subject'], terms)
columns = ('id', 'forum', 'topic', 'time', 'author', 'body', 'subject')
sql = ("SELECT m.id, m.forum, m.topic, m.time, m.author, m.body, "
"t.subject "
"FROM message m "
"LEFT JOIN "
"(SELECT subject, id "
"FROM topic) t "
"ON t.id = m.topic "
"WHERE %s" % (query))
self.log.debug(sql)
cursor.execute(sql, args)
for row in cursor:
row = dict(zip(columns, row))
row['time'] = to_datetime(row['time'], utc)
yield (req.href.discussion('message', row['id']) + '#%s' % (
row['id']), "Message #%d: %s" % (row['id'], shorten_line(
row['subject'])), row['time'], row['author'], shorten_result(
row['body'], [query]))
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:48,代码来源:search.py
示例17: _render_editor
def _render_editor(self, req, milestone):
# Suggest a default due time of 18:00 in the user's timezone
now = datetime.now(req.tz)
default_due = datetime(now.year, now.month, now.day, 18)
if now.hour > 18:
default_due += timedelta(days=1)
default_due = to_datetime(default_due, req.tz)
data = {
'milestone': milestone,
'datetime_hint': get_datetime_format_hint(req.lc_time),
'default_due': default_due,
'milestone_groups': [],
}
if milestone.exists:
req.perm(milestone.resource).require('MILESTONE_MODIFY')
milestones = [m for m in Milestone.select(self.env)
if m.name != milestone.name
and 'MILESTONE_VIEW' in req.perm(m.resource)]
data['milestone_groups'] = group_milestones(milestones,
'TICKET_ADMIN' in req.perm)
else:
req.perm(milestone.resource).require('MILESTONE_CREATE')
chrome = Chrome(self.env)
chrome.add_jquery_ui(req)
chrome.add_wiki_toolbars(req)
return 'milestone_edit.html', data, None
开发者ID:nextview,项目名称:medicticket,代码行数:29,代码来源:roadmap.py
示例18: get_blog_comments
def get_blog_comments(env, post_name='', from_dt=None, to_dt=None):
""" Returns comments as a list of tuples from search based on
AND input for post_name, and datetime span (from_dt and to_dt):
(post_name, number, comment, author, time)
Instantiate BlogComment objects to get further details of each.
Example of sorting the output by time, newest first:
from trac.util.compat import sorted, itemgetter
comments = get_blog_comments(env)
sorted(comments, key=itemgetter(4), reverse=True) """
# Build the list of WHERE restrictions
args = [post_name and ("name=%s", post_name) or None,
from_dt and ("time>%s", to_timestamp(from_dt)) or None,
to_dt and ("time<%s", to_timestamp(to_dt)) or None]
args = [arg for arg in args if arg]
where_clause = ""
where_values = None
if args:
where_clause = "WHERE " + " AND ".join([arg[0] for arg in args])
where_values = tuple([arg[1] for arg in args])
# Do the SELECT
cnx = env.get_db_cnx()
cursor = cnx.cursor()
sql = "SELECT name, number, comment, author, time " \
"FROM fullblog_comments " + where_clause
env.log.debug("get_blog_comments() SQL: %r (%r)" % (sql, where_values))
cursor.execute(sql, where_values or None)
# Return the items we have found
return [(row[0], row[1], row[2], row[3], to_datetime(row[4], utc))
for row in cursor]
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:32,代码来源:model.py
示例19: user_locked
def user_locked(self, user):
"""Returns whether the user account is currently locked.
Expect True, if locked, False, if not and None otherwise.
"""
if not self.login_attempt_max_count > 0:
# Account locking turned off by configuration.
return None
count = self.failed_count(user, reset=None)
ts_release = self.release_time(user)
if count < self.login_attempt_max_count:
self.log.debug(
"AcctMgr:user_locked(%s): False (try left)" % user)
return False
else:
if ts_release is None:
# Account locked permanently.
self.log.debug(
"AcctMgr:user_locked(%s): True (permanently)" % user)
return True
# Time-locked or time-lock expired.
ts_now = to_utimestamp(to_datetime(None))
self.log.debug(
"AcctMgr:user_locked(%s): %s" % (user, (ts_release - ts_now > 0)))
return (ts_release - ts_now > 0)
开发者ID:lkraav,项目名称:trachacks,代码行数:25,代码来源:guard.py
示例20: failed_count
def failed_count(self, user, ipnr=None, reset=False):
"""Report number of previously logged failed login attempts.
Enforce login policy with regards to tracking of login attempts
and user account lock behavior.
Default `False` for reset value causes logging of another attempt.
`None` value for reset just reads failed login attempts count.
`True` value for reset triggers final log deletion.
"""
value = get_user_attribute(self.env, user, 1, 'failed_logins_count')
count = value and int(value[user][1].get('failed_logins_count')) or 0
if reset is None:
# Report failed attempts count only.
return count
if not reset:
# Trigger the failed attempt logger.
attempts = self.get_failed_log(user)
log_length = len(attempts)
if log_length > self.login_attempt_max_count:
# Truncate attempts list preserving most recent events.
del attempts[:(log_length - self.login_attempt_max_count)]
attempts.append({'ipnr': ipnr,
'time': to_utimestamp(to_datetime(None))})
count += 1
# Update or create attempts counter and list.
set_user_attribute(self.env, user, 'failed_logins', str(attempts))
set_user_attribute(self.env, user, 'failed_logins_count', count)
self.log.debug("AcctMgr:failed_count(%s): %s" % (user, count))
else:
# Delete existing attempts counter and list.
del_user_attribute(self.env, user, 1, 'failed_logins')
del_user_attribute(self.env, user, 1, 'failed_logins_count')
# Delete the lock count too.
self.lock_count(user, 'reset')
return count
开发者ID:lkraav,项目名称:trachacks,代码行数:35,代码来源:guard.py
注:本文中的trac.util.datefmt.to_datetime函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论