From c9c0e930df0fb11725d15c4561fd12a612369bcd Mon Sep 17 00:00:00 2001 From: F-G Fernandez <26927750+frgfm@users.noreply.github.com> Date: Wed, 6 Dec 2023 22:07:01 +0100 Subject: [PATCH] refactor: Reverts DTZ --- pyproject.toml | 1 - src/app/api/api_v1/endpoints/guidelines.py | 10 +++------- src/app/api/api_v1/endpoints/repos.py | 4 ++-- src/app/core/security.py | 4 ++-- src/app/services/openai.py | 4 ++-- src/tests/test_security.py | 6 +++--- 6 files changed, 12 insertions(+), 17 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index dd83908..29e4e5d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -76,7 +76,6 @@ select = [ "ASYNC", # flake8-async "BLE", # flake8-blind-except "A", # flake8-builtins - "DTZ", # flake8-datetimez "ICN", # flake8-import-conventions "PIE", # flake8-pie "ARG", # flake8-unused-arguments diff --git a/src/app/api/api_v1/endpoints/guidelines.py b/src/app/api/api_v1/endpoints/guidelines.py index c22f1c4..9ff5d62 100644 --- a/src/app/api/api_v1/endpoints/guidelines.py +++ b/src/app/api/api_v1/endpoints/guidelines.py @@ -3,7 +3,7 @@ # All rights reserved. # Copying and/or distributing is strictly prohibited without the express permission of its copyright owner. -from datetime import datetime, timezone +from datetime import datetime from typing import List, cast from fastapi import APIRouter, Depends, Path, Security, status @@ -72,9 +72,7 @@ async def update_guideline_content( repos: RepositoryCRUD = Depends(get_repo_crud), user: User = Security(get_current_user, scopes=[UserScope.USER, UserScope.ADMIN]), ) -> Guideline: - guideline = await guidelines.update( - guideline_id, ContentUpdate(**payload.dict(), updated_at=datetime.now(tz=timezone.utc)) - ) + guideline = await guidelines.update(guideline_id, ContentUpdate(**payload.dict(), updated_at=datetime.utcnow())) telemetry_client.capture(user.id, event="guideline-content", properties={"repo_id": guideline.repo_id}) # Check if user is allowed repo = cast(Repository, await repos.get(guideline.repo_id, strict=True)) @@ -91,9 +89,7 @@ async def update_guideline_order( repos: RepositoryCRUD = Depends(get_repo_crud), user: User = Security(get_current_user, scopes=[UserScope.USER, UserScope.ADMIN]), ) -> Guideline: - guideline = await guidelines.update( - guideline_id, OrderUpdate(order=order_idx, updated_at=datetime.now(tz=timezone.utc)) - ) + guideline = await guidelines.update(guideline_id, OrderUpdate(order=order_idx, updated_at=datetime.utcnow())) telemetry_client.capture(user.id, event="guideline-order", properties={"repo_id": guideline.repo_id}) # Check if user is allowed repo = cast(Repository, await repos.get(guideline.repo_id, strict=True)) diff --git a/src/app/api/api_v1/endpoints/repos.py b/src/app/api/api_v1/endpoints/repos.py index 5160331..72a2427 100644 --- a/src/app/api/api_v1/endpoints/repos.py +++ b/src/app/api/api_v1/endpoints/repos.py @@ -5,7 +5,7 @@ import logging from base64 import b64decode -from datetime import datetime, timezone +from datetime import datetime from typing import List, cast from fastapi import APIRouter, Depends, HTTPException, Path, Security, status @@ -106,7 +106,7 @@ async def reorder_repo_guidelines( gh_client.check_user_permission(user, repo.full_name, repo.owner_id, payload.github_token, repo.installed_by) # Update all order return [ - await guidelines.update(guideline_id, OrderUpdate(order=order_idx, updated_at=datetime.now(tz=timezone.utc))) + await guidelines.update(guideline_id, OrderUpdate(order=order_idx, updated_at=datetime.utcnow())) for order_idx, guideline_id in enumerate(payload.guideline_ids) ] diff --git a/src/app/core/security.py b/src/app/core/security.py index 48829fa..7705b46 100644 --- a/src/app/core/security.py +++ b/src/app/core/security.py @@ -3,7 +3,7 @@ # All rights reserved. # Copying and/or distributing is strictly prohibited without the express permission of its copyright owner. -from datetime import datetime, timedelta, timezone +from datetime import datetime, timedelta from typing import Any, Dict, Optional from jose import jwt @@ -19,7 +19,7 @@ async def create_access_token(content: Dict[str, Any], expires_minutes: Optional[int] = None) -> str: """Encode content dict using security algorithm, setting expiration.""" expire_delta = timedelta(minutes=expires_minutes or settings.ACCESS_TOKEN_EXPIRE_MINUTES) - expire = datetime.now(tz=timezone.utc) + expire_delta + expire = datetime.utcnow() + expire_delta return jwt.encode({**content, "exp": expire}, settings.SECRET_KEY, algorithm=settings.JWT_ENCODING_ALGORITHM) diff --git a/src/app/services/openai.py b/src/app/services/openai.py index fe6237e..10d5c65 100644 --- a/src/app/services/openai.py +++ b/src/app/services/openai.py @@ -6,7 +6,7 @@ import json import logging from concurrent.futures import ThreadPoolExecutor -from datetime import datetime, timezone +from datetime import datetime from enum import Enum from typing import Any, Dict, List, Union @@ -165,7 +165,7 @@ def __init__( self.temperature = temperature self.frequency_penalty = frequency_penalty logger.info( - f"Using OpenAI model: {self.model} (created at {datetime.fromtimestamp(model_card.json()['created'], tz=timezone.utc).isoformat()})", + f"Using OpenAI model: {self.model} (created at {datetime.fromtimestamp(model_card.json()['created']).isoformat()})", ) @staticmethod diff --git a/src/tests/test_security.py b/src/tests/test_security.py index 8626ee2..f75dc10 100644 --- a/src/tests/test_security.py +++ b/src/tests/test_security.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta, timezone +from datetime import datetime, timedelta import pytest from jose import jwt @@ -37,10 +37,10 @@ async def test_verify_password(): @pytest.mark.asyncio() async def test_create_access_token(content, expires_minutes, expected_delta): payload = await create_access_token(content, expires_minutes) - after = datetime.now(tz=timezone.utc) + after = datetime.utcnow() assert isinstance(payload, str) decoded_data = jwt.decode(payload, settings.SECRET_KEY) # Verify data integrity assert all(v == decoded_data[k] for k, v in content.items()) # Check expiration - assert datetime.fromtimestamp(decoded_data["exp"], tz=timezone.utc) - timedelta(minutes=expected_delta) < after + assert datetime.utcfromtimestamp(decoded_data["exp"]) - timedelta(minutes=expected_delta) < after