本文整理汇总了Python中DateTime.DateTime.asdatetime方法的典型用法代码示例。如果您正苦于以下问题:Python DateTime.asdatetime方法的具体用法?Python DateTime.asdatetime怎么用?Python DateTime.asdatetime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DateTime.DateTime
的用法示例。
在下文中一共展示了DateTime.asdatetime方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: authenticateCredentials
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
def authenticateCredentials(self, credentials):
"""
Check if the user.password_date is older than validity_period.
If validity_period is 0, skip the check
"""
login = credentials.get('login')
if not login:
return None
self._invalidatePrincipalCache(login)
user = api.user.get(username=login)
if not user:
return None
registry = getUtility(IRegistry)
validity_period = registry['collective.pwexpiry.validity_period']
if validity_period == 0:
return None
# Ignore Managers
if user.has_role('Manager'):
return None
password_date = user.getProperty('password_date', '2000/01/01')
if str(password_date) != '2000/01/01':
current_time = DateTime()
since_last_pw_reset = days_since_event(password_date.asdatetime(),
current_time.asdatetime())
# Password has expired
if validity_period - since_last_pw_reset < 0:
self.REQUEST.RESPONSE.setHeader('user_expired', user.getId())
raise Unauthorized
return None
示例2: convert_to_datetime
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
def convert_to_datetime(date):
if date in (None, 'None'):
return None
if isinstance(date, basestring):
date = DateTime(date)
if isinstance(date, DateTime):
date = date.asdatetime()
return date
示例3: testBasicTZ
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
def testBasicTZ(self):
# psycopg2 supplies it's own tzinfo instances, with no `zone` attribute
tz = FixedOffset(60, 'GMT+1')
dt1 = datetime(2008, 8, 5, 12, 0, tzinfo=tz)
DT = DateTime(dt1)
dt2 = DT.asdatetime()
offset1 = dt1.tzinfo.utcoffset(dt1)
offset2 = dt2.tzinfo.utcoffset(dt2)
self.assertEqual(offset1, offset2)
示例4: booking_date
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
def booking_date(self):
''' Compute the booking date as passed in the request
'''
booking_date = self.request.form.get('booking_date', DateTime())
if not booking_date:
return []
if isinstance(booking_date, basestring):
booking_date = DateTime(booking_date)
return booking_date.asdatetime().date()
示例5: testConversions
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
def testConversions(self):
sdt0 = datetime.now() # this is a timezone naive datetime
dt0 = DateTime(sdt0)
self.assertTrue(dt0.timezoneNaive(), (sdt0, dt0))
sdt1 = datetime(2007, 10, 4, 18, 14, 42, 580, pytz.utc)
dt1 = DateTime(sdt1)
self.assertFalse(dt1.timezoneNaive(), (sdt1, dt1))
# convert back
sdt2 = dt0.asdatetime()
self.assertEqual(sdt0, sdt2)
sdt3 = dt1.utcdatetime() # this returns a timezone naive datetime
self.assertEqual(sdt1.hour, sdt3.hour)
dt4 = DateTime('2007-10-04T10:00:00+05:00')
sdt4 = datetime(2007, 10, 4, 5, 0)
self.assertEqual(dt4.utcdatetime(), sdt4)
self.assertEqual(dt4.asdatetime(), sdt4.replace(tzinfo=pytz.utc))
dt5 = DateTime('2007-10-23 10:00:00 US/Eastern')
tz = pytz.timezone('US/Eastern')
sdt5 = datetime(2007, 10, 23, 10, 0, tzinfo=tz)
dt6 = DateTime(sdt5)
self.assertEqual(dt5.asdatetime(), sdt5)
self.assertEqual(dt6.asdatetime(), sdt5)
self.assertEqual(dt5, dt6)
self.assertEqual(dt5.asdatetime().tzinfo, tz)
self.assertEqual(dt6.asdatetime().tzinfo, tz)
示例6: create
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
def create(self,description,location_uid,date,time,duration,private,member=None):
if getToolByName(self.context, 'portal_membership').isAnonymousUser():
return self.template()
if private == 'True':
private = '1'
else:
private = '0'
id = str(random.randint(1, 10000))
eid = "gf-event-"+date+"-"+id+"-"+private
if len(description) > 40:
description = description[0:40] + "..."
# Time Setup
fTime = time.split(":")
start = DateTime(date + " " + time + " US/CENTRAL")
end = DateTime(start)
tmp = end.asdatetime() + datetime.timedelta(minutes=int(duration))
end = DateTime(tmp)
#_createObjectByType bypasses permission security.
_createObjectByType("GroupFinderEvent", self.context, id=eid, title=description, location=location_uid)
obj = self.context.get(eid, None)
obj.setTitle(description)
obj.setLocation(location_uid)
if member == None:
member = getToolByName(self.context, 'portal_membership').getAuthenticatedMember()
obj.setCreators(["Confidential",member.getUserName(),member.getUserName()])
obj.setAttendees(member.getUserName())
else:
name = member.split('@')
staff = getToolByName(self.context, 'portal_membership').getAuthenticatedMember()
obj.setCreators(["Staff",name[0],staff.getUserName()])
obj.setAttendees(name[0])
obj.setStartDate(start)
obj.setEndDate(end)
obj.reindexObject()
示例7: notify_and_expire
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
def notify_and_expire():
"""
For each registered user check all the conditions and execute
the notification action
"""
portal = api.portal.get()
registry = getUtility(IRegistry)
validity_period = registry['collective.pwexpiry.validity_period']
notifications_to_use = set()
if 'collective.pwexpiry.notification_actions' in registry:
notifications_to_use = registry['collective.pwexpiry.notification_actions']
current_time = portal.ZopeTime()
local_tz = current_time.timezone()
for user_id in portal.acl_users.source_users.getUserIds():
user = portal.portal_membership.getMemberById(user_id)
password_date = DateTime(user.getProperty('password_date', '2000/01/01'))
last_notification_date = DateTime(user.getProperty('last_notification_date', '2000/01/01'))
last_notification_date = last_notification_date.toZone(local_tz)
if str(password_date) == DateTime('2000/01/01'):
# The user has not set the changed the password yet - the current time
# is set as the initial value
user.setMemberProperties({'password_date': current_time})
logger.info('Set new password reset date for user: %s' % user_id)
else:
# Counting days difference since the user reset his password
since_last_pw_reset = days_since_event(password_date.asdatetime(),
current_time.asdatetime())
# Counting days difference since the notification has been sent to the user
since_last_notification = days_since_event(last_notification_date.asdatetime(),
current_time.asdatetime())
# Number of days before the user's password expires
days_to_expire = validity_period - since_last_pw_reset
# Search for registered notifications and execute them
notifications = getAdapters((portal,), IExpirationCheck)
for notification_name, notification in notifications:
if notifications_to_use and notification_name not in notifications_to_use:
msg = ("Skipping notification %s because it is not in "
"registry['collective.pwexpiry.notification_actions']")
logger.debug(msg % notification_name)
continue
if notification(days_to_expire):
try:
# Protection of sending the expired notification email twice
pwres_to_notif = days_since_event(password_date.asdatetime(),
last_notification_date.asdatetime())
if pwres_to_notif > validity_period:
logger.warning('Omitting notification for user: \'%s\' ' \
'because the expiration email has already ' \
'been sent once.'% (user_id))
break
# Protection of sending the notification email twice
if since_last_notification < 1:
logger.warning('Omitting notification for user: \'%s\' ' \
'because the notification has been already ' \
'sent today.'% (user_id))
break
# Executing the notification action and updating user's property
notification.notification_action(user, days_to_expire)
logger.info('Triggered %s action for user: %s' % (
notification_name, user_id)
)
user.setMemberProperties({'last_notification_date': current_time})
except Exception, exc:
# Continue with the script even in case of problems
logger.error('Error while performing notification: %s ' \
'for user: %s: %s' % (notification_name, user_id, exc))
continue
示例8: TestSyndication
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
class TestSyndication(EEAContentTypeTestCase):
""" Test-cases for syndication. """
def afterSetUp(self):
""" Set up
"""
self.setRoles('Manager')
self.workflow = self.portal.portal_workflow
self.effective_date = DateTime(year=2008, month=4, day=3)
self.start_date = DateTime(year=2007, month=1, day=1)
self.folder.invokeFactory('Document', id='doc')
doc = self.folder.doc
doc.setTitle('Some Document')
doc.setEffectiveDate(self.effective_date)
doc.reindexObject()
self.folder.invokeFactory('QuickEvent', id='event')
event = self.folder.event
event.setTitle('Some Event')
event.setLocation(location)
event.setEffectiveDate(self.effective_date)
event.setStartDate(self.start_date)
event.reindexObject()
def getFeedItem(self, context, doc):
""" getFeedItem
"""
adapter = queryMultiAdapter((doc, context), IFeedItem)
if adapter is None:
adapter = BaseItem(doc, context)
return adapter
def testTitle(self):
""" Title
"""
entry = self.getFeedItem(self.folder, self.folder.doc)
self.assertEquals(entry.title, 'Some Document')
entry = self.getFeedItem(self.folder, self.folder.event)
self.assertEquals(entry.title, 'Some Event')
def testDate(self):
""" Date
"""
entry = self.getFeedItem(self.folder, self.folder.doc)
ed = self.effective_date.asdatetime().replace(microsecond=0)
effective_date = DateTime(ed).utcdatetime()
self.assertEquals(entry.published.utcdatetime(), effective_date)
entry = self.getFeedItem(self.folder, self.folder.event)
sd = self.folder.event.start().asdatetime().replace(microsecond=0)
start_date = DateTime(sd).utcdatetime()
self.assertEquals(entry.published.utcdatetime(), start_date)
def testFolderThumb(self):
""" Folder thumb
"""
# simulate publications which are folders
self.folder.invokeFactory(
'Image', id='img1', image=image, title='Simple Image')
view = self.folder.restrictedTraverse('@@rss.xml')
entry = self.getFeedItem(self.folder, self.folder)
self.failUnless('img' in view.getItemDescription(entry))
def testHighlightThumb(self):
""" Highlight thumb
"""
highlight = self.folder[self.folder.invokeFactory(
'Highlight', id='h1', title='Highlight')]
highlight.setImage(image)
view = highlight.restrictedTraverse('@@rss.xml')
entry = self.getFeedItem(self.folder, highlight)
self.failUnless('img' in view.getItemDescription(entry))
示例9: DashboardView
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
#.........这里部分代码省略.........
'assigned': '#dcdcdc',
'attachment_due': '#dcdcdc',
'open': '#dcdcdc',
_('Results pending'): '#dcdcdc',
'rejected': '#FF6B6B',
'retracted': '#FF6B6B',
_('Rejected'): '#FF6B6B',
_('Retracted'): '#FF6B6B',
'to_be_verified': '#A7DBD8',
_('To be verified'): '#A7DBD8',
'verified': '#69D2E7',
_('Verified'): '#69D2E7',
'published': '#83AF9B',
_('Published'): '#83AF9B',
}
def _getDateStr(self, period, created):
if period == 'y':
created = created.year()
elif period == 'b':
m = (((created.month()-1)/6)*6)+1
created = '%s-%s' % (str(created.year())[2:], str(m).zfill(2))
elif period == 'q':
m = (((created.month()-1)/3)*3)+1
created = '%s-%s' % (str(created.year())[2:], str(m).zfill(2))
elif period == 'm':
created = '%s-%s' % (str(created.year())[2:], str(created.month()).zfill(2))
elif period == 'w':
d = (((created.day()-1)/7)*7)+1
year, weeknum, dow = created.asdatetime().isocalendar()
created = created - dow
created = '%s-%s-%s' % (str(created.year())[2:], str(created.month()).zfill(2), str(created.day()).zfill(2))
elif period == 'a':
# All time, but evolution chart grouped by year
created = created.year()
else:
created = '%s-%s-%s' % (str(created.year())[2:], str(created.month()).zfill(2), str(created.day()).zfill(2))
return created
def _fill_dates_evo(self, catalog, query):
outevoidx = {}
outevo = []
days = 1
if self.periodicity == 'y':
days = 336
elif self.periodicity == 'b':
days = 168
elif self.periodicity == 'q':
days = 84
elif self.periodicity == 'm':
days = 28
elif self.periodicity == 'w':
days = 7
elif self.periodicity == 'a':
days = 336
otherstate = _('Other status')
statesmap = self.get_states_map(query['portal_type'])
stats = statesmap.values()
stats.sort()
stats.append(otherstate)
statscount = {s:0 for s in stats}
示例10: index_html
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
def index_html(self, REQUEST):
""" """
uid = REQUEST.form.get('uid')
date_for_roles = REQUEST.form.get('date_for_roles')
if "," in uid:
user = None
roles = None
multi = json.dumps({'users': uid.split(",")})
else:
multi = None
user, roles = self._prepare_user_page(uid)
is_auth = _is_authenticated(REQUEST)
# we can only connect to ldap with bind=True if we have an
# authenticated user
agent = self._get_ldap_agent(bind=is_auth)
user_dn = agent._user_dn(uid)
log_entries = list(reversed(agent._get_metadata(user_dn)))
VIEWS = {}
filtered_roles = set([info[0] for info in roles]) # + owner_roles)
if date_for_roles:
filter_date = DateTime(date_for_roles).asdatetime().date()
else:
filter_date = DateTime().asdatetime().date()
for entry in log_entries:
date = DateTime(entry['timestamp']).toZone("CET")
entry['timestamp'] = date.ISO()
view = VIEWS.get(entry['action'])
if not view:
view = getMultiAdapter((self, self.REQUEST),
name="details_" + entry['action'])
VIEWS[entry['action']] = view
entry['view'] = view
_roles = entry.get('data', {}).get('roles')
_role = entry.get('data', {}).get('role')
if date.asdatetime().date() >= filter_date:
if entry['action'] == 'ENABLE_ACCOUNT':
filtered_roles.difference_update(set(_roles))
elif entry['action'] == "DISABLE_ACCOUNT":
filtered_roles.update(set(_roles))
elif entry['action'] in ["ADDED_TO_ROLE"]:
if _role and _role in filtered_roles:
filtered_roles.remove(_role)
elif entry['action'] in ["REMOVED_FROM_ROLE"]:
if _role:
filtered_roles.add(_role)
output = []
for entry in log_entries:
if output:
last_entry = output[-1]
check = ['author', 'action']
flag = True
for k in check:
if last_entry[k] != entry[k]:
flag = False
break
if flag:
last_entry['data'].append(entry['data'])
else:
entry['data'] = [entry['data']]
output.append(entry)
else:
entry['data'] = [entry['data']]
output.append(entry)
removed_roles = []
if user.get('status') == 'disabled':
# process log entries to list the roles the user had before
# being disabled
for entry in log_entries:
if entry['action'] == 'DISABLE_ACCOUNT':
for role in entry['data'][0]['roles']:
try:
role_description = agent.role_info(role)[
'description']
except:
role_description = ("This role doesn't exist "
"anymore")
removed_roles.append((role, role_description))
break
return self._render_template(
"zpt/userdetails/index.zpt", context=self,
filtered_roles=filtered_roles, user=user, roles=roles,
removed_roles=removed_roles, multi=multi, log_entries=output)
示例11: verifyToken
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
def verifyToken(self, token, login, max_seats, request, response):
""" Activates a token by putting it in the tokens[] array of mapping1[login] if it is not already present. """
alsoProvides(request, IDisableCSRFProtection)
isVerified = False # it is verified if it is already in the active tokens list server-side
seat_timeout = 5 # default if there is a problem with the member property
iTokens = 0 # assume no tokens are active until proven otherwise
existing = self.mapping1.get(login)
if existing and 'tokens' in existing:
iTokens = len( existing['tokens'] )
isVerified = token in existing['tokens']
if self.DEBUG:
print "authenticateCredentials():: cookie_val is " + token + ", and active tokens are: " + ', '.join( existing['tokens'] )
else:
self.mapping1[login] = { 'tokens':[] } # initialize tokens array for this login
if self.DEBUG:
print "verifyToken:: login = %s, active = %i, max = %i" % (login, iTokens, max_seats)
try:
# for seats > 1, use member property for cookie timeout value
seat_timeout = self.getSeatTimeoutInMinutesForLogin(login)
td_seat_timeout = datetime.timedelta(minutes=seat_timeout)
except:
pass
# if this is the last token to issue,
# then go ahead and clear stale tokens for this login
if not isVerified and iTokens >= max_seats - 1:
self.clearStaleTokens(login)
try:
from_ip = self.get_ip(request)
except:
traceback.print_exc()
if isVerified:
# just extend it
now = DateTime()
self.mapping2[token] = {'userid': login, 'ip': from_ip, 'startTime': now, 'expireTime': DateTime( now.asdatetime() + td_seat_timeout )}
if self.DEBUG:
print "verifyToken:: logon= %s, IP= %s, startTime= %s, expireTime= %s" % ( self.mapping2.get(token)['userid'], from_ip, self.mapping2.get(token)['startTime'], self.mapping2.get(token)['expireTime'] )
elif iTokens < max_seats:
now = DateTime()
# if it already exists, add it
self.mapping1[login]['tokens'].append( token )
self.mapping2[token] = {'userid': login, 'ip': from_ip, 'startTime': now, 'expireTime': DateTime( now.asdatetime() + td_seat_timeout )}
if self.DEBUG:
print "verifyToken:: after activate token, active tokens = " + ', '.join(self.mapping1[login]['tokens'])
# since this was activated, just ensure that the cookie in the browser reflects what is server side
self.setCookie( token )
else:
# cannot issue cookie, so clear in browser-side
#self.setCookie('')
# if the token is not able to be issued because of max_seats filled,
# then force logout, and show the message
# Logout the
# user by calling resetCredentials. Note that this
# will eventually call our own resetCredentials which
# will cleanup our own cookie.
try:
self.resetAllCredentials(request, response)
self._getPAS().plone_utils.addPortalMessage(_(
u"The maximum number of simultaneous logins for this user has been exceeded. You have been \
logged out."), "error")
except:
traceback.print_exc()
示例12: getSeatsPropertiesForLogin
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
def getSeatsPropertiesForLogin(self, login):
# initialize max_seats at 1
max_seats = 1
seat_timeout = 5 # initialize to 5 minutes
if self.login_member_data_mapping is None:
self.login_member_data_mapping = OOBTree() # if this has not been initialized then do it now
if self.DEBUG:
print "Initialized the Login Member Data Mapping"
# if the max_seats has a valid cached value, then use it
cached_member_data = self.login_member_data_mapping.get(login, None)
now = DateTime()
if cached_member_data and 'expireTime' in cached_member_data and 'maxSeats' in cached_member_data and 'seatTimeoutInMinutes' in cached_member_data and now < cached_member_data['expireTime']:
max_seats = cached_member_data['maxSeats']
seat_timeout = cached_member_data['seatTimeoutInMinutes']
else:
member = self.getMember(login)
# get the max_seats property from the member data tool
if member is not None:
max_seats = member.getProperty("max_seats")
seat_timeout = member.getProperty("seat_timeout_in_minutes")
# cache the max_seats for login
td_seat_timeout = datetime.timedelta(minutes=seat_timeout)
self.login_member_data_mapping[login] = { 'maxSeats': int( max_seats ), 'seatTimeoutInMinutes': float( seat_timeout ), 'expireTime': DateTime( now.asdatetime() + td_seat_timeout )}
return { 'maxSeats': int( max_seats ), 'seatTimeoutInMinutes': float( seat_timeout ) }
示例13: authenticateCredentials
# 需要导入模块: from DateTime import DateTime [as 别名]
# 或者: from DateTime.DateTime import asdatetime [as 别名]
#.........这里部分代码省略.........
timeout=session_source.timeout,
mod_auth_tkt=session_source.mod_auth_tkt)
if ticket_data is not None:
break
if ticket_data is None:
return None
(digest, userid, tokens, user_data, timestamp) = ticket_data
pas = self._getPAS()
info = pas._verifyUser(pas.plugins, user_id=userid)
if info is None:
return None
login = info['login']
cookie_val = self.getCookie()
# get max seats from member data property or cache and default to 1 if not set
try:
max_seats = self.getMaxSeatsForLogin(login)
except:
traceback.print_exc()
# When debugging, print the maxSeats value that was resolved
if self.DEBUG:
print "authenticateCredentials():: Max Seats is " + str( max_seats )
if max_seats == 1:
if cookie_val:
# A cookie value is there. If it's the same as the value
# in our mapping, it's fine. Otherwise we'll force a
# logout.
existing = self.mapping1.get(login, None)
if self.DEBUG:
if existing:
print "authenticateCredentials():: cookie_val is " + cookie_val + ", and active tokens are: " + ', '.join( existing['tokens'] )
if existing and cookie_val not in existing['tokens']:
# The cookies values differ, we want to logout the
# user by calling resetCredentials. Note that this
# will eventually call our own resetCredentials which
# will cleanup our own cookie.
try:
self.resetAllCredentials(request, response)
pas_instance.plone_utils.addPortalMessage(_(
u"Someone else logged in under your name. You have been \
logged out"), "error")
except:
traceback.print_exc()
elif existing is None:
# The browser has the cookie but we don't know about
# it. Let's reset our own cookie:
self.setCookie('')
else:
# When no cookie is present, we generate one, store it and
# set it in the response:
cookie_val = uuid()
# do some cleanup in our mappings
existing = self.mapping1.get(login)
if existing and 'tokens' in existing:
try:
if existing['tokens'][0] in self.mapping2:
del self.mapping2[existing['tokens'][0]]
except:
pass
try:
from_ip = self.get_ip( request )
except:
traceback.print_exc()
now = DateTime()
self.mapping1[login] = { 'tokens':[] }
self.mapping1[login]['tokens'].append( cookie_val )
self.mapping2[cookie_val] = {'userid': login, 'ip': from_ip, 'startTime': now, 'expireTime': DateTime( now.asdatetime() + self.time_to_persist_cookies )}
self.setCookie(cookie_val)
else:
# Max seats is not 1. Treat this as a floating licenses scenario.
# Nobody is logged out, but once the max seats threshold is reached,
# active tokens must expire before new users may log in.
if cookie_val:
# When the cookie value is there, try to verify it or activate it if is it not added yet
self.verifyToken( cookie_val, login, max_seats, request, response )
else:
if self.DEBUG:
print "authenticateCredentials:: Try to issue a token because there is no cookie value."
# When no cookie is present, attempt to issue a token and use the cookie to store it
self.issueToken(login, max_seats, request, response)
# if max_seats are filled, then force logout
if self.isLoginAtCapacity(login, max_seats):
self.forceLogoutForUser(login, request, response)
return None # Note that we never return anything useful