Skip to content

Commit

Permalink
rpl datetime.utcnow() w datetime.now(timezone.utc)
Browse files Browse the repository at this point in the history
  • Loading branch information
Lescurel committed Dec 29, 2024
1 parent 1cf017a commit 227c76e
Show file tree
Hide file tree
Showing 14 changed files with 48 additions and 42 deletions.
12 changes: 8 additions & 4 deletions api/src/change_phone_request.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging
from collections import defaultdict
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from random import randint

from dispatch_sms import NoAuthConfigured, send_validation_code
Expand All @@ -15,7 +15,7 @@


def change_phone_request(member_id: int | None, phone: str) -> int:
now = datetime.utcnow()
now = datetime.now(timezone.utc)

try:
phone = normalise_phone_number(phone)
Expand Down Expand Up @@ -88,7 +88,11 @@ def change_phone_request(member_id: int | None, phone: str) -> int:
raise BadRequest("Misslyckades med att skicka sms med verifikations kod")

change_request = PhoneNumberChangeRequest(
member_id=member_id, phone=phone, validation_code=validation_code, completed=False, timestamp=datetime.utcnow()
member_id=member_id,
phone=phone,
validation_code=validation_code,
completed=False,
timestamp=datetime.now(timezone.utc),
)

db_session.add(change_request)
Expand All @@ -104,7 +108,7 @@ def change_phone_request(member_id: int | None, phone: str) -> int:

def change_phone_validate(member_id: int | None, request_id: int, validation_code: str):
logging.info(f"member {member_id} validating phone number, code {validation_code}")
now = datetime.utcnow()
now = datetime.now(timezone.utc)

try:
change_request = (
Expand Down
6 changes: 3 additions & 3 deletions api/src/core/auth.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import secrets
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from logging import getLogger
from string import ascii_letters, digits
from typing import Optional
Expand Down Expand Up @@ -57,7 +57,7 @@ def create_access_token(ip: str, browser: Optional[str], user_id: int, valid_dur
access_token=generate_token(),
browser=browser,
ip=ip,
expires=datetime.utcnow() + (timedelta(minutes=15) if valid_duration is None else valid_duration),
expires=datetime.now(timezone.utc) + (timedelta(minutes=15) if valid_duration is None else valid_duration),
lifetime=int(timedelta(days=14).total_seconds()),
)

Expand Down Expand Up @@ -122,7 +122,7 @@ def password_reset(reset_token, unhashed_password):
except MultipleResultsFound:
raise InternalServerError(log=f"Multiple tokens {reset_token} found, this is a bug.")

if datetime.utcnow() - password_reset_token.created_at > timedelta(minutes=10):
if datetime.now(timezone.utc) - password_reset_token.created_at > timedelta(minutes=10):
raise UnprocessableEntity("Reset link expired, try to request a new one.")

try:
Expand Down
12 changes: 6 additions & 6 deletions api/src/dispatch_emails.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import time
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
from contextlib import closing
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from os.path import abspath, dirname
from time import sleep
from typing import Optional
Expand Down Expand Up @@ -88,7 +88,7 @@ def send_messages(key: Optional[str], domain: str, sender: str, to_override: Opt

if response.ok:
message.status = Message.SENT
message.sent_at = datetime.utcnow()
message.sent_at = datetime.now(timezone.utc)

db_session.add(message)
db_session.commit()
Expand All @@ -104,7 +104,7 @@ def send_messages(key: Optional[str], domain: str, sender: str, to_override: Opt

def already_sent_message(template: MessageTemplate, member: Member, days: int):
"""True if a message has been sent with the given template to the member in the last #days days"""
now = datetime.utcnow()
now = datetime.now(timezone.utc)
reminder_sent = (
db_session.query(Message)
.filter(
Expand All @@ -118,7 +118,7 @@ def already_sent_message(template: MessageTemplate, member: Member, days: int):


def labaccess_reminder() -> None:
now = datetime.utcnow()
now = datetime.now(timezone.utc)

end_date_reminder_target = now.date() + timedelta(days=LABACCESS_REMINDER_DAYS_BEFORE)

Expand Down Expand Up @@ -172,7 +172,7 @@ def labaccess_reminder() -> None:


def membership_reminder() -> None:
now = datetime.utcnow().date()
now = datetime.now(timezone.utc).date()

members, memberships = get_members_and_membership()
members = list(members)
Expand Down Expand Up @@ -227,7 +227,7 @@ def quiz_reminders() -> None:
# Assume quiz 1 is the get started quiz
quiz_id = 1
quiz_members = quiz_member_answer_stats(quiz_id)
now = datetime.utcnow()
now = datetime.now(timezone.utc)

members, memberships = get_members_and_membership()
id_to_member = {member.member_id: (member, membership) for member, membership in zip(members, memberships)}
Expand Down
4 changes: 2 additions & 2 deletions api/src/init_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
from contextlib import closing
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone

from core.auth import generate_token
from core.models import AccessToken
Expand Down Expand Up @@ -44,7 +44,7 @@ def refresh_service_access_tokens(session_factory):
raise Exception(f"Found multiple of service token id {service_user.id}, this is a bug.") from e

access_token.lifetime = ten_years.total_seconds()
access_token.expires = datetime.utcnow() + ten_years
access_token.expires = datetime.now(timezone.utc) + ten_years

session.add(access_token)
else:
Expand Down
4 changes: 2 additions & 2 deletions api/src/migrate.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import re
from collections import namedtuple
from contextlib import closing
from datetime import datetime
from datetime import datetime, timezone
from inspect import getfile, getmodule, stack
from os import listdir
from os.path import dirname, exists, isdir, join
Expand Down Expand Up @@ -119,7 +119,7 @@ def run_migrations(session_factory):

session.execute(
"INSERT INTO migrations VALUES (:id, :name, :applied_at)",
{"id": migration.id, "name": migration.name, "applied_at": datetime.utcnow()},
{"id": migration.id, "name": migration.name, "applied_at": datetime.now(timezone.utc)},
)
session.commit()
except Exception:
Expand Down
6 changes: 3 additions & 3 deletions api/src/multiaccess/box_terminator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import date, datetime, timedelta
from datetime import date, datetime, timedelta, timezone

from membership.models import Box, Member, Span
from messages.message import send_message
Expand Down Expand Up @@ -98,7 +98,7 @@ def box_terminator_nag(member_number=None, box_label_id=None, nag_type=None):
days_after_expiration=(today - end_date).days,
)

box.last_nag_at = datetime.utcnow()
box.last_nag_at = datetime.now(timezone.utc)


def box_terminator_validate(member_number=None, box_label_id=None, session_token=None):
Expand All @@ -114,7 +114,7 @@ def box_terminator_validate(member_number=None, box_label_id=None, session_token

box = Box(member_id=member.member_id, box_label_id=box_label_id)

box.last_check_at = datetime.utcnow()
box.last_check_at = datetime.now(timezone.utc)
box.session_token = session_token
db_session.add(box)
db_session.flush()
Expand Down
6 changes: 3 additions & 3 deletions api/src/service/auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone

import membership.member_auth
from core.models import AccessToken
Expand Down Expand Up @@ -37,7 +37,7 @@ def authenticate_request() -> None:
if not access_token:
raise Unauthorized("Unauthorized, invalid access token.", fields="bearer", what=BAD_VALUE)

now = datetime.utcnow()
now = datetime.now(timezone.utc)
if access_token.expires < now:
db_session.query(AccessToken).filter(AccessToken.expires < now).delete()
raise Unauthorized("Unauthorized, expired access token.", fields="bearer", what=EXPIRED)
Expand All @@ -60,7 +60,7 @@ def authenticate_request() -> None:

access_token.ip = request.remote_addr
access_token.browser = request.user_agent.string
access_token.expires = datetime.utcnow() + timedelta(seconds=access_token.lifetime)
access_token.expires = datetime.now(timezone.utc) + timedelta(seconds=access_token.lifetime)

g.user_id = access_token.user_id
g.session_token = access_token.access_token
Expand Down
4 changes: 2 additions & 2 deletions api/src/service/entity.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from base64 import b64decode, b64encode
from collections import namedtuple
from datetime import date, datetime
from datetime import date, datetime, timezone
from decimal import Decimal
from logging import getLogger
from math import ceil
Expand Down Expand Up @@ -340,7 +340,7 @@ def delete(self, entity_id: int, commit: bool = True) -> None:
raise NotFound("Could not find any entity with specified parameters.")

if not entity.deleted_at:
entity.deleted_at = datetime.utcnow()
entity.deleted_at = datetime.now(timezone.utc)

if commit:
db_session.commit()
Expand Down
6 changes: 3 additions & 3 deletions api/src/service/traffic_logger.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
from datetime import datetime
from datetime import datetime, timezone
from typing import List

from flask import Request as FlaskRequest
Expand All @@ -20,7 +20,7 @@ class TrafficLogger:
service_traffic: List[object]

def __init__(self) -> None:
self.create_time = datetime.utcnow().isoformat() + "Z"
self.create_time = datetime.now(timezone.utc).isoformat() + "Z"
self.service_traffic = list()

def log_service_traffic(self, traffic: Response) -> None:
Expand All @@ -47,7 +47,7 @@ def commit(self, session_request: FlaskRequest, session_response: FlaskResponse)
"query": session_request.args,
}
session_response_data = {
"date": datetime.utcnow().isoformat() + "Z",
"date": datetime.now(timezone.utc).isoformat() + "Z",
"status": session_response.status_code,
"headers": dict(session_response.headers),
}
Expand Down
8 changes: 5 additions & 3 deletions api/src/shop/pay.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import re
from dataclasses import dataclass
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from logging import getLogger
from typing import Any, List, Optional
Expand Down Expand Up @@ -247,7 +247,9 @@ def cleanup_pending_members(relevant_email: str) -> None:
db_session.query(Member)
.filter(
(Member.pending_activation == True)
& ((Member.email == relevant_email) | (Member.created_at < datetime.utcnow() - timedelta(hours=1))),
& (
(Member.email == relevant_email) | (Member.created_at < datetime.now(timezone.utc) - timedelta(hours=1))
),
)
.all()
)
Expand Down Expand Up @@ -314,7 +316,7 @@ def register(data_dict: Any, remote_addr: str, user_agent: str) -> RegisterRespo
# Mark the member as deleted, so that it is not visible in the member list, and it cannot be used to log in
# We cannot pass the deleted_at parameter to the create function because it the API prevents that field from being set.
member = db_session.query(Member).filter(Member.member_id == member_id).one()
member.deleted_at = datetime.utcnow()
member.deleted_at = datetime.now(timezone.utc)
db_session.flush()

token = auth.force_login(remote_addr, user_agent, member_id)["access_token"]
Expand Down
2 changes: 1 addition & 1 deletion api/src/shop/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ def pending_action_value_sum(member_id: int, action_type: str) -> int:

def complete_pending_action(action: TransactionAction) -> None:
action.status = TransactionAction.COMPLETED
action.completed_at = datetime.utcnow()
action.completed_at = datetime.now(timezone.utc)
db_session.add(action)
db_session.flush()

Expand Down
4 changes: 2 additions & 2 deletions api/src/systest/api/box_terminator_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import datetime, timezone
from random import randint
from unittest import skip

Expand Down Expand Up @@ -90,7 +90,7 @@ def test_box_terminator_validate_status_active(self):
def test_box_terminator_validate_deleted_span_is_filtered(self):
member = self.db.create_member()
box = self.db.create_box()
span = self.db.create_span(enddate=self.date(10), type=Span.LABACCESS, deleted_at=datetime.utcnow())
span = self.db.create_span(enddate=self.date(10), type=Span.LABACCESS, deleted_at=datetime.now(timezone.utc))

self.api.post(
"/multiaccess/box-terminator/validate-box",
Expand Down
12 changes: 6 additions & 6 deletions api/src/systest/api/change_phone_request_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import random
from datetime import datetime, timedelta
from datetime import datetime, timedelta, timezone
from random import randint
from time import sleep
from unittest import skip
Expand All @@ -16,7 +16,7 @@
class Test(ApiTest):
@patch("change_phone_request.send_validation_code")
def test_request_and_validate(self, mock_send_validation_code):
now = datetime.utcnow()
now = datetime.now(timezone.utc)
new_phone = "+461234567"
member = self.db.create_member()
old_phone = member.phone
Expand Down Expand Up @@ -71,7 +71,7 @@ def test_request_high_num_one_member(self, mock_send_validation_code):

@patch("change_phone_request.send_validation_code")
def test_validate_wrong_code(self, mock_send_validation_code):
now = datetime.utcnow()
now = datetime.now(timezone.utc)
new_phone = "+461234567"
member = self.db.create_member()
old_phone = member.phone
Expand Down Expand Up @@ -111,7 +111,7 @@ def test_validate_wrong_code(self, mock_send_validation_code):

@patch("change_phone_request.send_validation_code")
def test_validate_already_used_code(self, mock_send_validation_code):
now = datetime.utcnow()
now = datetime.now(timezone.utc)
new_phone = "+461234567"
member = self.db.create_member()
old_phone = member.phone
Expand Down Expand Up @@ -152,7 +152,7 @@ def test_validate_already_used_code(self, mock_send_validation_code):

@patch("change_phone_request.send_validation_code")
def test_validate_mult_reqs_one_member(self, mock_send_validation_code):
now = datetime.utcnow()
now = datetime.now(timezone.utc)
member = self.db.create_member()
self.db.create_phone_request(timestamp=now - timedelta(hours=1))
self.db.create_phone_request(timestamp=now - timedelta(hours=2))
Expand Down Expand Up @@ -193,7 +193,7 @@ def test_validate_mult_reqs_one_member(self, mock_send_validation_code):

@patch("change_phone_request.send_validation_code")
def test_validate_mult_reqs_mult_members(self, mock_send_validation_code):
now = datetime.utcnow()
now = datetime.now(timezone.utc)
num_members = 20

member = [None] * num_members
Expand Down
4 changes: 2 additions & 2 deletions api/src/test_aid/test_base.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import time
from copy import copy
from datetime import date, datetime, timedelta
from datetime import date, datetime, timedelta, timezone
from unittest import TestCase

from flask import Flask
Expand All @@ -27,7 +27,7 @@ def setUpClass(self) -> None:
super().setUpClass()
self.obj = ObjFactory(self)

self.now = datetime.utcnow()
self.now = datetime.now(timezone.utc)
self.today = self.now.date()

@classinstancemethod
Expand Down

0 comments on commit 227c76e

Please sign in to comment.