本文整理匯總了Python中django.utils.timezone.timedelta方法的典型用法代碼示例。如果您正苦於以下問題:Python timezone.timedelta方法的具體用法?Python timezone.timedelta怎麽用?Python timezone.timedelta使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.utils.timezone
的用法示例。
在下文中一共展示了timezone.timedelta方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_email_weekly_command_digest_day
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def test_email_weekly_command_digest_day(self):
"""Test that admin can send digest on the weekly digest day."""
setattr(settings, 'DIGEST_WEEKLY_DAY', 0)
previous = timezone.now()
static = previous
# find the next scheduled digest day
while static.weekday() != 0:
static += timezone.timedelta(days=1)
with patch('openach.management.commands.senddigest.timezone.now') as timezone_mock:
timezone_mock.return_value = static
logger.debug('Shifted timezone.now() from weekday %s to %s', previous.weekday(), static.weekday())
create_board(board_title='New Board', days=-1)
call_command('senddigest', 'weekly')
self.assertEqual(len(mail.outbox), 1, 'No weekly digest email sent')
示例2: test_email_weekly_command_other_day
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def test_email_weekly_command_other_day(self):
"""Test that admin cannot digest email not on weekly digest day unless forced."""
setattr(settings, 'DIGEST_WEEKLY_DAY', 0)
previous = timezone.now()
static = previous
# make sure we're not on a scheduled digest day
while static.weekday() == 0:
static += timezone.timedelta(days=1)
with patch('openach.management.commands.senddigest.timezone.now') as timezone_mock:
timezone_mock.return_value = static
logger.debug('Shifted timezone.now() from weekday %s to %s', previous.weekday(), static.weekday())
create_board(board_title='New Board', days=-1)
call_command('senddigest', 'weekly')
self.assertEqual(len(mail.outbox), 0, 'Weekly digest email sent on wrong day')
call_command('senddigest', 'weekly', '--force')
self.assertEqual(len(mail.outbox), 1, 'Weekly digest email not sent when forced')
示例3: test_get_queryset
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def test_get_queryset(self):
# no authentication
response = self.client_unauthenticated.get(self.url)
self.assertEqual(403, response.status_code)
# ok
# participant 3 has read the 2 last messages, 1 only the first
p1 = Participation.objects.create(participant=self.participant3, thread=self.thread3)
p1.date_last_check = now() - timedelta(days=1)
p1.save()
p2 = Participation.objects.create(participant=self.participant1, thread=self.thread3)
p2.date_last_check = now() - timedelta(days=2)
p2.save()
response = self.client_authenticated.get(self.url)
self.assertEqual(200, response.status_code)
messages_dct = parse_json_response(response.data)
messages = messages_dct["results"]
self.assertEqual(3, len(messages))
self.assertEqual(messages[0]["id"], self.m33.id)
self.assertEqual(messages[1]["id"], self.m22.id)
self.assertEqual(messages[2]["id"], self.m11.id)
self.assertEqual([], messages[0]["readers"])
self.assertEqual(messages[0]["is_notification"], True) # not read
self.assertEqual(messages[1]["is_notification"], False) # because written by the user himself
self.assertEqual(messages[2]["is_notification"], False) # because written by the user himself
示例4: test_list_messages_in_thread
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def test_list_messages_in_thread(self):
# no authentication
response = self.client_unauthenticated.get("{0}{1}/list_messages_in_thread/".format(self.url, self.thread1.id))
self.assertEqual(403, response.status_code)
# no permission
response = self.client_authenticated.get("{0}{1}/list_messages_in_thread/".format(self.url, self.thread_unrelated.id))
self.assertEqual(403, response.status_code)
# ok
# participant 3 has read the 2 last messages, 1 only the first
p1 = Participation.objects.create(participant=self.participant3, thread=self.thread3)
p1.date_last_check = now() - timedelta(days=1)
p1.save()
p2 = Participation.objects.create(participant=self.participant1, thread=self.thread3)
p2.date_last_check = now() - timedelta(days=2)
p2.save()
# we change the date of the messages
self.m31.sent_at = p1.date_last_check = now() - timedelta(days=3)
self.m31.save()
self.m32.sent_at = p1.date_last_check = now() - timedelta(days=1, hours=12)
self.m32.save()
response = self.client_authenticated.get("{0}{1}/list_messages_in_thread/".format(self.url, self.thread3.id))
messages_dct = parse_json_response(response.data)
messages = messages_dct["results"]
self.assertEqual([self.m33.id, self.m32.id, self.m31.id], [m["id"] for m in messages])
self.assertEqual([set([]), set([self.participant3.id]), set([self.participant1.id, self.participant3.id])], [set(m["readers"]) for m in messages])
示例5: test_check_callback_and_save
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def test_check_callback_and_save(self):
# we ensure a user may by default not send more than 50 messages a day
Message.objects.filter(sender=self.participant1).count()
r = 100
for i in range(r):
try:
m = Message(sender=self.participant1, thread=self.thread1, body="hi")
m.save()
except Exception:
pass
# we have more than 50 messages (more in setUp)
self.assertEqual(50, Message.objects.filter(sender=self.participant1).count())
# the limit is only in the last 24 hours
Message.objects.filter(sender=self.participant1).update(sent_at=now() - timedelta(days=1, seconds=1))
last = Message.objects.filter(sender=self.participant1).latest('id')
new = Message.objects.create(sender=self.participant1, thread=self.thread1, body="hi")
self.assertEqual(new.id, last.id + 1)
示例6: test_get_lasts_messages_of_threads_check_is_notification_check_who_read
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def test_get_lasts_messages_of_threads_check_is_notification_check_who_read(self):
# participant 1 and 2 have read the messages, 3 no
self.participation1.date_last_check = now() + timedelta(days=1)
self.participation1.save()
self.participation2.date_last_check = now() + timedelta(days=1)
self.participation2.save()
# we create a notification check
with self.assertNumQueries(6):
messages = Message.managers.get_lasts_messages_of_threads(self.participant1.id, check_who_read=True, check_is_notification=True)
# the ordering has not been modified
self.assertEqual([self.m33.id, self.m22.id, self.m11.id], [m.id for m in messages])
# the second conversation has no notification because last reply comes from the current participant
self.assertEqual(messages[1].is_notification, False)
# the third (first in ordering) conversation has new messages
self.assertEqual(messages[0].is_notification, True)
# participant 1 and 2 have read Thread 1
self.assertTrue(self.participant1.id in messages[2].readers)
示例7: test_inactive_user_cleanup
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def test_inactive_user_cleanup(self):
def create_users(kind):
logintime = timezone.now() + timezone.timedelta(seconds=5)
kwargs_list = [
dict(email=f'user1+{kind}@example.com', is_active=False, last_login=None),
dict(email=f'user2+{kind}@example.com', is_active=True, last_login=None),
dict(email=f'user3+{kind}@example.com', is_active=False, last_login=logintime),
dict(email=f'user4+{kind}@example.com', is_active=True, last_login=logintime),
]
return (User.objects.create(**kwargs) for kwargs in kwargs_list)
# Old users
faketime = timezone.now() - settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE - timezone.timedelta(seconds=1)
with mock.patch('django.db.models.fields.timezone.now', return_value=faketime):
expired_user, _, _, _ = create_users('old')
# New users
create_users('new')
all_users = set(User.objects.all())
management.call_command('chores')
# Check that only the expired user was deleted
self.assertEqual(all_users - set(User.objects.all()), {expired_user})
示例8: test_homepage_search
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def test_homepage_search(client):
event = f.EventFactory(is_published=True, name='test_event')
f.EventFactory(is_published=True, start_date=timezone.now()-timezone.timedelta(days=9),
end_date=timezone.now()-timezone.timedelta(days=8))
url = reverse('home')
response = client.get(url, {'q': 'test'})
assert response.status_code == 200
# should have 'events' in the template context
assert 'events' in response.context
assert 'upcoming_events' in response.context
assert 'past_events' in response.context
assert len(response.context['events']) == 1
assert len(response.context['upcoming_events']) == 0
assert len(response.context['past_events']) == 0
assert response.context['events'][0].id == event.id
示例9: test_query_events_with_zero_events
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def test_query_events_with_zero_events(graphql_client, conference_factory):
now = timezone.now()
conference = conference_factory(start=now, end=now + timezone.timedelta(days=3))
resp = graphql_client.query(
"""query($code: String!) {
conference(code: $code) {
events {
slug
}
}
}""",
variables={"code": conference.code},
)
assert not resp.get("errors")
assert len(resp["data"]["conference"]["events"]) == 0
示例10: test_query_events_image
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def test_query_events_image(rf, graphql_client, conference_factory, event_factory):
now = timezone.now()
request = rf.get("/")
conference = conference_factory(start=now, end=now + timezone.timedelta(days=3))
event = event_factory(conference=conference, latitude=1, longitude=1)
resp = graphql_client.query(
"""query($code: String!) {
conference(code: $code) {
events {
image
}
}
}""",
variables={"code": conference.code},
)
assert not resp.get("errors")
assert len(resp["data"]["conference"]["events"]) == 1
events = resp["data"]["conference"]["events"]
events[0]["image"] == get_image_url_from_request(request, event.image)
示例11: test_is_cfp_open
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def test_is_cfp_open(graphql_client, conference_factory, deadline_factory, cfp_open):
now = timezone.now()
conference = conference_factory(timezone=pytz.timezone("America/Los_Angeles"))
deadline_factory(
start=now - timezone.timedelta(days=1),
end=now + timezone.timedelta(days=1) if cfp_open else now,
conference=conference,
type="cfp",
)
resp = graphql_client.query(
"""
query($code: String!) {
conference(code: $code) {
isCFPOpen
}
}
""",
variables={"code": conference.code},
)
assert resp["data"]["conference"]["isCFPOpen"] is cfp_open
示例12: _create
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def _create(cls, model_class, *args, **kwargs):
specified_deadlines = {}
for deadline in Deadline.TYPES:
_type = deadline[0]
value = kwargs.pop(f"active_{_type}", None)
specified_deadlines[_type] = value
instance = super()._create(model_class, *args, **kwargs)
for _type, value in specified_deadlines.items():
if value is True:
instance.deadlines.add(DeadlineFactory(conference=instance, type=_type))
elif value is False:
instance.deadlines.add(
DeadlineFactory(
conference=instance,
type=_type,
start=timezone.now() - timezone.timedelta(days=10),
end=timezone.now() - timezone.timedelta(days=5),
)
)
return instance
示例13: get_usable_missed_message_address
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def get_usable_missed_message_address(address: str) -> MissedMessageEmailAddress:
token = get_missed_message_token_from_address(address)
try:
mm_address = MissedMessageEmailAddress.objects.select_related().get(
email_token=token,
timestamp__gt=timezone_now() - timedelta(seconds=MissedMessageEmailAddress.EXPIRY_SECONDS),
)
except MissedMessageEmailAddress.DoesNotExist:
raise ZulipEmailForwardError("Missed message address expired or doesn't exist.")
if not mm_address.is_usable():
# Technical, this also checks whether the event is expired,
# but that case is excluded by the logic above.
raise ZulipEmailForwardError("Missed message address out of uses.")
return mm_address
示例14: clean_history_data
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def clean_history_data():
"""
清除曆史數據
:return:
"""
logger.info('開始清理曆史數據')
lastweek = datetime.now() - timedelta(days=7)
last3month = datetime.now() - timedelta(days=90)
lastyear = datetime.now() - timedelta(days=365)
# (, 10),直接刪除
Article.objects.filter(site__star__lt=10, ctime__lte=lastweek).delete()
# [10, 20),創建時間超過 3 個月,內容置空
Article.objects.filter(site__star__gte=10, site__star__lt=20, ctime__lte=last3month).update(content=' ')
# [20, ),創建時間超過一年,內容置空
Article.objects.filter(site__star__gte=20, ctime__lte=lastyear).update(content=' ')
# 壓縮數據庫
vacuum_sqlite_db()
logger.info('曆史數據清理完畢')
示例15: delete_old_logs
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import timedelta [as 別名]
def delete_old_logs():
"""
Delete old log entries.
For performance reasons, we execute raw SQL against the LogEntry model's table.
This task runs every day.
"""
cutoff = timezone.now() - timezone.timedelta(days=settings.LOG_DELETION_DAYS)
query = (
"DELETE FROM {table} "
"WHERE {table}.created < '{cutoff}'::timestamptz".format(
table=LogEntry._meta.db_table,
cutoff=cutoff.isoformat(),
)
)
logger.info(query)
with connection.cursor() as cursor:
cursor.execute(query)