Change now() to timezone.now() throughout codebase.

Change `from django.utils.timezone import now` to
`from django.utils import timezone`.

This is both because now() is ambiguous (could be datetime.datetime.now),
and more importantly to make it easier to write a lint rule against
datetime.datetime.now().
This commit is contained in:
Rishi Gupta 2017-02-25 12:02:13 -08:00 committed by Tim Abbott
parent bf6415cf72
commit 15d60fa7ed
8 changed files with 27 additions and 30 deletions

View File

@ -15,7 +15,7 @@ from django.contrib.sites.models import Site
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.utils.translation import ugettext_lazy as _
from django.utils.timezone import now
from django.utils import timezone
from confirmation.util import get_status_field
from zerver.lib.utils import generate_random_token
@ -28,7 +28,7 @@ def check_key_is_valid(creation_key):
# type: (Text) -> bool
if not RealmCreationKey.objects.filter(creation_key=creation_key).exists():
return False
days_sofar = (now() - RealmCreationKey.objects.get(creation_key=creation_key).date_created).days
days_sofar = (timezone.now() - RealmCreationKey.objects.get(creation_key=creation_key).date_created).days
# Realm creation link expires after settings.REALM_CREATION_LINK_VALIDITY_DAYS
if days_sofar <= settings.REALM_CREATION_LINK_VALIDITY_DAYS:
return True
@ -50,7 +50,7 @@ def generate_activation_url(key, host=None):
def generate_realm_creation_url():
# type: () -> Text
key = generate_key()
RealmCreationKey.objects.create(creation_key=key, date_created=now())
RealmCreationKey.objects.create(creation_key=key, date_created=timezone.now())
return u'%s%s%s' % (settings.EXTERNAL_URI_SCHEME,
settings.EXTERNAL_HOST,
reverse('zerver.views.create_realm',
@ -67,7 +67,7 @@ class ConfirmationManager(models.Manager):
return False
max_days = self.get_link_validity_in_days()
time_elapsed = now() - confirmation.date_sent
time_elapsed = timezone.now() - confirmation.date_sent
if time_elapsed.total_seconds() > max_days * 24 * 3600:
return False
@ -81,7 +81,7 @@ class ConfirmationManager(models.Manager):
def get_link_for_object(self, obj, host=None):
# type: (Union[ContentType, int], Optional[str]) -> Text
key = generate_key()
self.create(content_object=obj, date_sent=now(), confirmation_key=key)
self.create(content_object=obj, date_sent=timezone.now(), confirmation_key=key)
return self.get_activation_url(key, host=host)
def get_activation_url(self, confirmation_key, host=None):
@ -138,7 +138,7 @@ class ConfirmationManager(models.Manager):
if html_template:
html_content = html_template.render(context)
send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [email_address], html_message=html_content)
return self.create(content_object=obj, date_sent=now(), confirmation_key=confirmation_key)
return self.create(content_object=obj, date_sent=timezone.now(), confirmation_key=confirmation_key)
class EmailChangeConfirmationManager(ConfirmationManager):
def get_activation_url(self, key, host=None):
@ -180,4 +180,4 @@ class EmailChangeConfirmation(Confirmation):
class RealmCreationKey(models.Model):
creation_key = models.CharField(_('activation key'), max_length=40)
date_created = models.DateTimeField(_('created'), default=now)
date_created = models.DateTimeField(_('created'), default=timezone.now)

View File

@ -8,13 +8,11 @@ var set_to_start_of_day = function (time) {
return time.setMilliseconds(0).setSeconds(0).setMinutes(0).setHours(0);
};
function now() { return new XDate(); }
// Given an XDate object 'time', return a two-element list containing
// - a string for the current human-formatted version
// - a boolean for if it will need to be updated when the day changes
exports.render_now = function (time) {
var start_of_today = set_to_start_of_day(now());
var start_of_today = set_to_start_of_day(new XDate());
var start_of_other_day = set_to_start_of_day(time.clone());
// How many days old is 'time'? 0 = today, 1 = yesterday, 7 = a
@ -51,7 +49,7 @@ var update_list = [];
// Represented as an XDate with hour, minute, second, millisecond 0.
var next_update;
$(function () {
next_update = set_to_start_of_day(now()).addDays(1);
next_update = set_to_start_of_day(new XDate()).addDays(1);
});
// time_above is an optional argument, to support dates that look like:
@ -103,7 +101,7 @@ exports.render_date = function (time, time_above) {
// This isn't expected to be called externally except manually for
// testing purposes.
exports.update_timestamps = function () {
var time = now();
var time = new XDate();
if (time >= next_update) {
var to_process = update_list;
update_list = [];

View File

@ -10,7 +10,7 @@ from zerver.models import UserProfile, get_client, get_user_profile_by_email
from zerver.lib.response import json_error, json_unauthorized, json_success
from django.shortcuts import resolve_url
from django.utils.decorators import available_attrs
from django.utils.timezone import now
from django.utils import timezone
from django.conf import settings
from zerver.lib.queue import queue_json_publish
from zerver.lib.timestamp import datetime_to_timestamp, timestamp_to_datetime
@ -84,7 +84,7 @@ def update_user_activity(request, user_profile):
event = {'query': query,
'user_profile_id': user_profile.id,
'time': datetime_to_timestamp(now()),
'time': datetime_to_timestamp(timezone.now()),
'client': request.client.name}
queue_json_publish("user_activity", event, lambda event: None)

View File

@ -49,7 +49,7 @@ from django.db.models.query import QuerySet
from django.core.exceptions import ValidationError
from importlib import import_module
from django.core.mail import EmailMessage
from django.utils.timezone import now
from django.utils import timezone
from confirmation.models import Confirmation, EmailChangeConfirmation
import six
@ -63,7 +63,6 @@ session_engine = import_module(settings.SESSION_ENGINE)
from zerver.lib.create_user import random_api_key
from zerver.lib.timestamp import timestamp_to_datetime, datetime_to_timestamp
from zerver.lib.queue import queue_json_publish
from django.utils import timezone
from zerver.lib.create_user import create_user
from zerver.lib import bugdown
from zerver.lib.cache import cache_with_key, cache_set, \
@ -263,7 +262,7 @@ def add_new_user_history(user_profile, streams):
"""Give you the last 100 messages on your public streams, so you have
something to look at in your home view once you finish the
tutorial."""
one_week_ago = now() - datetime.timedelta(weeks=1)
one_week_ago = timezone.now() - datetime.timedelta(weeks=1)
recipients = Recipient.objects.filter(type=Recipient.STREAM,
type_id__in=[stream.id for stream in streams
if not stream.invite_only])
@ -345,7 +344,7 @@ def process_new_human_user(user_profile, prereg_user=None, newsletter_data=None)
'NAME': user_profile.full_name,
'REALM_ID': user_profile.realm_id,
'OPTIN_IP': newsletter_data["IP"],
'OPTIN_TIME': datetime.datetime.isoformat(now().replace(microsecond=0)),
'OPTIN_TIME': datetime.datetime.isoformat(timezone.now().replace(microsecond=0)),
},
},
lambda event: None)
@ -2822,10 +2821,10 @@ def do_update_message(user_profile, message, subject, propagate_mode, content, r
# We only change messages up to 2 days in the past, to avoid hammering our
# DB by changing an unbounded amount of messages
if propagate_mode == 'change_all':
before_bound = now() - datetime.timedelta(days=2)
before_bound = timezone.now() - datetime.timedelta(days=2)
propagate_query = (propagate_query & ~Q(id = message.id) &
Q(pub_date__range=(before_bound, now())))
Q(pub_date__range=(before_bound, timezone.now())))
if propagate_mode == 'change_later':
propagate_query = propagate_query & Q(id__gt = message.id)

View File

@ -5,7 +5,7 @@ from typing import cast, AbstractSet, Any, Optional, Iterable, Sequence, Mapping
from django.utils.translation import ugettext as _
from django.conf import settings
from django.utils.timezone import now
from django.utils import timezone
from collections import deque
import datetime
import os
@ -677,7 +677,7 @@ def receiver_is_idle(user_profile_id, realm_presences):
else:
active_datetime = timestamp_to_datetime(latest_active_timestamp)
# 140 seconds is consistent with activity.js:OFFLINE_THRESHOLD_SECS
idle = now() - active_datetime > datetime.timedelta(seconds=140)
idle = timezone.now() - active_datetime > datetime.timedelta(seconds=140)
return off_zulip or idle

View File

@ -1,7 +1,7 @@
from __future__ import absolute_import
from django.utils.translation import ugettext as _
from django.utils.timezone import now
from django.utils import timezone
from django.conf import settings
from django.core import validators
from django.core.exceptions import ValidationError
@ -991,7 +991,7 @@ def update_message_backend(request, user_profile,
edit_limit_buffer = 20
if content is not None and user_profile.realm.message_content_edit_limit_seconds > 0:
deadline_seconds = user_profile.realm.message_content_edit_limit_seconds + edit_limit_buffer
if (now() - message.pub_date) > datetime.timedelta(seconds=deadline_seconds):
if (timezone.now() - message.pub_date) > datetime.timedelta(seconds=deadline_seconds):
raise JsonableError(_("The time limit for editing this message has past"))
if subject is None and content is None:

View File

@ -4,7 +4,7 @@ from typing import Optional
from django.conf import settings
from django.http import HttpRequest, HttpResponse
from django.utils.timezone import now
from django.utils import timezone
from django.utils.translation import ugettext as _
from zerver.lib.request import has_request_variables, REQ
@ -28,7 +28,7 @@ def add_push_device_token(request, user_profile, token_str, kind, ios_app_id=Non
kind=kind,
ios_app_id=ios_app_id))
if not created:
token.last_updated = now()
token.last_updated = timezone.now()
token.save(update_fields=['last_updated'])
return json_success()

View File

@ -3,7 +3,7 @@ from __future__ import division
from __future__ import print_function
from django.core.management.base import BaseCommand, CommandParser
from django.utils.timezone import now
from django.utils import timezone
from zerver.models import Message, UserProfile, Stream, Recipient, UserPresence, \
Subscription, get_huddle, Realm, UserMessage, RealmAlias, \
@ -193,7 +193,7 @@ class Command(BaseCommand):
# Populate users with some bar data
for user in user_profiles:
status = UserPresence.ACTIVE # type: int
date = now()
date = timezone.now()
client = get_client("website")
if user.full_name[0] <= 'H':
client = get_client("ZulipAndroid")
@ -405,7 +405,7 @@ def send_messages(data):
message.subject = stream.name + Text(random.randint(1, 3))
saved_data['subject'] = message.subject
message.pub_date = now()
message.pub_date = timezone.now()
do_send_messages([{'message': message}])
recipients[num_messages] = (message_type, message.recipient.id, saved_data)
@ -432,7 +432,7 @@ def create_user_presences(user_profiles):
# type: (Iterable[UserProfile]) -> None
for user in user_profiles:
status = 1 # type: int
date = now()
date = timezone.now()
client = get_client("website")
UserPresence.objects.get_or_create(
user_profile=user,