本文整理汇总了Python中utils.Utils.now方法的典型用法代码示例。如果您正苦于以下问题:Python Utils.now方法的具体用法?Python Utils.now怎么用?Python Utils.now使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类utils.Utils
的用法示例。
在下文中一共展示了Utils.now方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: schedule
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def schedule(cls, date=None, status=None, fallback='Probably', priority=None):
# If no date is specified, look for the next invitation that is no
# later than saturday
if date is None:
upcoming = Invitation.query(Invitation.date >= Utils.now().date()).\
order(Invitation.date).get()
if upcoming is None or upcoming.date > Utils.saturday().date():
logging.info('No future invitation found.')
return None
else:
date = upcoming.date
schedule = cls.query(cls.date==date).filter(cls.status=='Yes').get() or \
Invitation.resolve(when=date, priority=priority) or \
cls.query(cls.date==date).get() or \
Gamenight(status=fallback,
date=date,
lastupdate=Utils.now())
if status is not None and schedule.status != 'Yes':
schedule.status = status
schedule.put()
logging.info('Scheduling new gamenight: %r', schedule)
return schedule
示例2: test_sync_directories
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def test_sync_directories(self):
sourceFiles = ['/movie/transformers', '/movie/transformers/transformers.mp4']
target = '/users/willsam100/Desktop/'
ftpMock = FTP('')
ftpMock.retrbinary = MagicMock()
ftpMock.nlst = MagicMock(return_value=[])
now = util.now()
targetDir = util.join(target, util.basename(sourceFiles[0]))
targetFile = util.join(targetDir, util.basename(sourceFiles[1]))
self.__cleanUp__(targetDir)
utilMock = Utils();
def splitDirectoriesAndFiles(*args):
def secondCall_splitDirectoriesAndFiles(*args):
return ([], sourceFiles[1:])
utilMock.splitDirectoriesAndFiles.side_effect = secondCall_splitDirectoriesAndFiles
return ([sourceFiles[0]], [])
utilMock.splitDirectoriesAndFiles = MagicMock(side_effect=splitDirectoriesAndFiles)
utilMock.exists = MagicMock(return_value=False)
utilMock.computeSpeed = MagicMock(return_value=40)
utilMock.now = MagicMock(return_value=now)
transfer = Transfer(ftpMock, utilMock, target)
transfer.sync(sourceFiles)
utilMock.splitDirectoriesAndFiles.call_args_list == (mock.call(ftpMock, targetDir), mock.call(ftpMock, targetFile))
utilMock.splitDirectoriesAndFiles.assert_called_with(ftpMock, [])
utilMock.exists.call_args_list == [mock.call(targetDir), mock.call(targetFile)]
ftpMock.retrbinary.assert_called_with('RETR ' + sourceFiles[1], mock.ANY)
self.assertTrue(util.exists(targetFile))
self.__cleanUp__(targetDir)
utilMock.computeSpeed.assert_called_with(now, targetFile)
示例3: test_sync_files
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def test_sync_files(self):
sourceFiles = ['/movie/transformers.mp4']
target = '/users/willsam100/Desktop/'
ftpMock = FTP('')
ftpMock.retrbinary = MagicMock()
now = util.now()
targetFile = util.join(target, util.basename(sourceFiles[0]))
self.__cleanUp__(targetFile)
utilMock = Utils();
utilMock.splitDirectoriesAndFiles = MagicMock(return_value=([], sourceFiles))
utilMock.exists = MagicMock(return_value=False)
utilMock.computeSpeed = MagicMock(return_value=40)
utilMock.now = MagicMock(return_value=now)
transfer = Transfer(ftpMock, utilMock, target)
transfer.sync(sourceFiles)
utilMock.splitDirectoriesAndFiles.assert_called_with(ftpMock, sourceFiles)
utilMock.exists.assert_called_with(targetFile)
ftpMock.retrbinary.assert_called_with('RETR ' + sourceFiles[0], mock.ANY)
self.assertTrue(util.exists(targetFile))
self.__cleanUp__(targetFile)
utilMock.computeSpeed.assert_called_with(now, targetFile)
示例4: text_date
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def text_date(self):
date = datetime.datetime.combine(self.date, self.time)
#if self.date == Utils.now().date().today():
# return self.time.strftime('Today, %I:%M %p')
if datetime.timedelta(0) < date - Utils.now() < datetime.timedelta(6):
return date.strftime('%A, %I:%M %p')
return date.strftime('%b %d, %I:%M %p')
示例5: make_gamenight
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def make_gamenight(self, overwrite=False):
"""Create an unsaved gamenight object from an invitation.
Args:
overwrite - if an existing GN is already scheduled, replace it. If
false, return it unchanged.
"""
gamenight = Gamenight.query(Gamenight.date==self.date).get()
if gamenight and not overwrite:
if gamenight.status == 'Yes':
return gamenight
if not gamenight:
gamenight = Gamenight(date=self.date)
gamenight.invitation = self.key
gamenight.status = 'Yes'
gamenight.lastupdate = Utils.now()
gamenight.time = self.time
gamenight.owner = self.owner
gamenight.location = self.location
gamenight.notes = self.notes
return gamenight
示例6: get
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def get(self):
days = defaultdict(dict)
for gn in Gamenight.future(10):
days[gn.date]['date'] = gn.date
days[gn.date]['scheduled'] = True
days[gn.date]['status'] = gn.status
days[gn.date]['owner'] = gn.owner
days[gn.date]['time'] = gn.time
days[gn.date]['where'] = gn.location
invitations = Invitation.query(Invitation.date >= Utils.now()).\
order(Invitation.date).iter()
for invite in invitations:
if not days[invite.date].get('invitations'):
days[invite.date]['date'] = invite.date
days[invite.date]['invitations'] = []
days[invite.date]['invitations'].append(invite)
day_sorter = lambda x: x.get('date')
template_values = { 'days': sorted(days.values(), key=day_sorter) }
current_user = users.get_current_user()
if current_user:
user = User.get(users.get_current_user())
template_values.update({
'logout': users.create_logout_url('/'),
'user': user,
})
template = JINJA_ENVIRONMNT.get_template('schedule.html')
self.response.write(template.render(template_values))
示例7: resolve
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def resolve(cls, when=Utils.saturday(), history=4, priority=None):
"""Figure out where GN should be at the given date.
By default, consider the last 4 to give preference to people who
haven't been hosting."""
if type(when) != datetime.date:
when = when.date()
logging.info('Resolving gamenight for %s', when)
invitations = cls.query(cls.date == when)
logging.debug('Query: %r' % invitations)
if priority is not None:
priorities = (priority,)
else:
priorities = ('Insist', 'Want', 'Can')
candidates = []
# check each level separately
for pri in priorities:
candidates = dict([(x.owner.id(), x) for x in
invitations.filter(cls.priority == pri).fetch()])
# no matches at this priority
if not candidates:
logging.debug('none at priority %s' % pri)
continue
# no need to look at lower levels
logging.debug('Candidates(%s): %r' % (pri, candidates))
break
# no one wants to host :(
if not candidates:
logging.debug('none found.')
return None
# more than one option, filter out the recent hosts until we run out of
# recent hosts, or have just one option left.
logging.debug('Candidates: %r' % candidates.keys())
if len(candidates) > 1:
if history:
old_nights = Gamenight.query(Gamenight.date < Utils.now()).\
order(Gamenight.date).fetch(history)
while old_nights and len(candidates) > 1:
owner = old_nights.pop().owner.id()
if owner in candidates:
logging.debug('removing previous host %s' % owner)
del candidates[owner]
logging.debug('Not recent candidates: %r' % candidates.keys())
# pick one at random, return the invitation object
selected = random.choice(candidates.keys())
logging.debug('Selected invitation: %s\n%r' %
(selected, candidates[selected]))
return candidates[selected].make_gamenight()
示例8: summary
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def summary(cls):
"""Get upcoming saturdays, and who has invited.
Returns a dictionary of dates, with a list of (who, priority) for each.
"""
invitations = cls.query(cls.date >= Utils.now()).\
filter(cls.date < Utils.now() +
datetime.timedelta(weeks=8)).\
order(cls.date)
res = {}
invlist = defaultdict(list)
for invite in invitations.iter():
invlist[invite.date].append(invite.owner.get().name)
for date, invites in invlist.iteritems():
res[date] = ', '.join(name for name in invites)
return res
示例9: reset
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def reset(cls, date=None):
if date is None:
date = Utils.saturday()
schedule = Invitation.resolve(when=date, priority='Insist') or \
cls.query(cls.date==date).get() or \
Gamenight(status='Probably',
date=date,
lastupdate=Utils.now())
schedule.put()
logging.info('Resetting gamenight page: %r', schedule)
return schedule
示例10: is_this_week
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def is_this_week(self):
return self.date - Utils.now().today().date() < datetime.timedelta(7)
示例11: future
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def future(cls, limit):
return cls.query(cls.date >= Utils.now()).order(cls.date).fetch(limit)
示例12: post
# 需要导入模块: from utils import Utils [as 别名]
# 或者: from utils.Utils import now [as 别名]
def post(self, template_values={}):
user = User.get(users.get_current_user())
if self.request.get('withdraw'):
invite = Invitation.get(self.request.get('withdraw'))
if not invite:
self.get(error="Can't find this invitation.")
return
if invite.owner != user.key and not user.superuser:
self.get(error='Not your invitation.')
return
msg = ''
gn = Gamenight.query(Gamenight.invitation==invite.key).get()
logging.info('Invite id: %s, gn: %s', invite.key, gn)
invite.key.delete()
msg = 'Invitation withdrawn. '
if gn:
gn.key.delete()
msg += 'Rescheduling gamenight. '
Gamenight.schedule()
self.get(msg=msg)
return
args = {}
for k in ['when', 'where', 'priority', 'notes']:
args[k] = self.request.get(k)
error = None
warning = None
msg = ''
if args['when']:
try:
orig = args['when']
args['when'] = parser.parse(args['when'].replace('today', ''))
logging.info('Parsed "%s" as "%s"', orig, args['when'])
except ValueError:
error = 'Not sure what you mean by "%s"' % args['when']
logging.error('Failed to parse when: %s', args['when'])
else:
checks = []
if not time(18, 0, 0) <= args['when'].time() <= time(21, 0, 0):
checks.append(args['when'].time().strftime('%I:%M %p'))
if args['when'].date().weekday() != 5:
checks.append(args['when'].date().strftime('%A'))
if args['when'].date() < Utils.now().date():
checks.append(args['when'].date().strftime('%x'))
if checks:
warning = 'Just checking, did you really mean %s?' % ', '.join(checks)
else:
error = 'When do you want to host?'
if error:
self.get(template_values=args, error=error)
return
if not args['where']:
error = 'Where do you want to host?'
self.get(template_values=args, error=error)
return
if not args['priority']:
error = '''Gotta have a priority. Also, don't mess with me.'''
self.get(template_values=args, error=error)
return
args['owner'] = user.key
updated, invite = Invitation.create(args)
if updated:
gn = Gamenight.query(Gamenight.invitation==invite.key).get()
if gn:
gn.update()
msg += 'Invitation and gamenight updated! '
else:
msg += 'Invitation updated! '
self.get(msg=msg, error=warning)
else:
msg += 'Invitation created! '
self.get(msg=msg, error=warning)