From 528e676e56cd02bc24f6f1cbb13e695f6295d7dc Mon Sep 17 00:00:00 2001 From: Christophe Bornet Date: Thu, 3 Oct 2024 16:22:25 +0200 Subject: [PATCH] ref: Add ruff rules for datetime (DTZ) (#4003) Add ruff rules for datetime (DTZ) --- src/backend/base/langflow/api/v1/files.py | 4 ++-- src/backend/base/langflow/api/v1/flows.py | 2 +- src/backend/base/langflow/initial_setup/setup.py | 9 ++++----- src/backend/base/langflow/schema/message.py | 2 +- src/backend/base/langflow/services/database/service.py | 6 +++--- src/backend/base/langflow/services/tracing/langfuse.py | 6 +++--- src/backend/base/pyproject.toml | 1 + 7 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/backend/base/langflow/api/v1/files.py b/src/backend/base/langflow/api/v1/files.py index 96ddec2d9..14152cdf4 100644 --- a/src/backend/base/langflow/api/v1/files.py +++ b/src/backend/base/langflow/api/v1/files.py @@ -1,5 +1,5 @@ import hashlib -from datetime import datetime +from datetime import datetime, timezone from http import HTTPStatus from io import BytesIO from pathlib import Path @@ -57,7 +57,7 @@ async def upload_file( raise HTTPException(status_code=403, detail="You don't have access to this flow") file_content = await file.read() - timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + timestamp = datetime.now(tz=timezone.utc).astimezone().strftime("%Y-%m-%d_%H-%M-%S") file_name = file.filename or hashlib.sha256(file_content).hexdigest() full_file_name = f"{timestamp}_{file_name}" folder = flow_id_str diff --git a/src/backend/base/langflow/api/v1/flows.py b/src/backend/base/langflow/api/v1/flows.py index 510b6e525..f955fe372 100644 --- a/src/backend/base/langflow/api/v1/flows.py +++ b/src/backend/base/langflow/api/v1/flows.py @@ -390,7 +390,7 @@ async def download_multiple_file( zip_stream.seek(0) # Generate the filename with the current datetime - current_time = datetime.now().strftime("%Y%m%d_%H%M%S") + current_time = datetime.now(tz=timezone.utc).astimezone().strftime("%Y%m%d_%H%M%S") filename = f"{current_time}_langflow_flows.zip" return StreamingResponse( diff --git a/src/backend/base/langflow/initial_setup/setup.py b/src/backend/base/langflow/initial_setup/setup.py index d44c16fc5..abbbeffa5 100644 --- a/src/backend/base/langflow/initial_setup/setup.py +++ b/src/backend/base/langflow/initial_setup/setup.py @@ -390,10 +390,9 @@ def get_project_data(project): project_is_component = project.get("is_component") project_updated_at = project.get("updated_at") if not project_updated_at: - project_updated_at = datetime.now(tz=timezone.utc).isoformat() - updated_at_datetime = datetime.strptime(project_updated_at, "%Y-%m-%dT%H:%M:%S.%f%z") + updated_at_datetime = datetime.now(tz=timezone.utc) else: - updated_at_datetime = datetime.strptime(project_updated_at, "%Y-%m-%dT%H:%M:%S.%f") + updated_at_datetime = datetime.fromisoformat(project_updated_at) project_data = project.get("data") project_icon = project.get("icon") project_icon = demojize(project_icon) if project_icon and purely_emoji(project_icon) else "" @@ -528,14 +527,14 @@ def load_flows_from_directory(): if hasattr(existing, key): # flow dict from json and db representation are not 100% the same setattr(existing, key, value) - existing.updated_at = datetime.utcnow() + existing.updated_at = datetime.now(tz=timezone.utc).astimezone() existing.user_id = user_id session.add(existing) else: logger.info(f"Creating new flow: {flow_id} with endpoint name {flow_endpoint_name}") flow["user_id"] = user_id flow = Flow.model_validate(flow, from_attributes=True) - flow.updated_at = datetime.utcnow() + flow.updated_at = datetime.now(tz=timezone.utc).astimezone() session.add(flow) diff --git a/src/backend/base/langflow/schema/message.py b/src/backend/base/langflow/schema/message.py index bf44627e7..cdc7f782f 100644 --- a/src/backend/base/langflow/schema/message.py +++ b/src/backend/base/langflow/schema/message.py @@ -29,7 +29,7 @@ def _timestamp_to_str(timestamp: datetime | str) -> str: if isinstance(timestamp, str): # Just check if the string is a valid datetime try: - datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") + datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") # noqa: DTZ007 return timestamp except ValueError as e: msg = f"Invalid timestamp: {timestamp}" diff --git a/src/backend/base/langflow/services/database/service.py b/src/backend/base/langflow/services/database/service.py index fd5b51291..970f1aa7b 100644 --- a/src/backend/base/langflow/services/database/service.py +++ b/src/backend/base/langflow/services/database/service.py @@ -2,7 +2,7 @@ from __future__ import annotations import time from contextlib import contextmanager -from datetime import datetime +from datetime import datetime, timezone from pathlib import Path from typing import TYPE_CHECKING @@ -206,7 +206,7 @@ class DatabaseService(Service): logger.info(f"Running DB migrations in {self.script_location}") try: - buffer.write(f"{datetime.now().isoformat()}: Checking migrations\n") + buffer.write(f"{datetime.now(tz=timezone.utc).astimezone().isoformat()}: Checking migrations\n") command.check(alembic_cfg) except Exception as exc: if isinstance(exc, util.exc.CommandError | util.exc.AutogenerateDiffsDetected): @@ -214,7 +214,7 @@ class DatabaseService(Service): time.sleep(3) try: - buffer.write(f"{datetime.now().isoformat()}: Checking migrations\n") + buffer.write(f"{datetime.now(tz=timezone.utc).astimezone()}: Checking migrations\n") command.check(alembic_cfg) except util.exc.AutogenerateDiffsDetected as exc: logger.error(f"AutogenerateDiffsDetected: {exc}") diff --git a/src/backend/base/langflow/services/tracing/langfuse.py b/src/backend/base/langflow/services/tracing/langfuse.py index 2ca8b7abc..65a89eaea 100644 --- a/src/backend/base/langflow/services/tracing/langfuse.py +++ b/src/backend/base/langflow/services/tracing/langfuse.py @@ -2,7 +2,7 @@ from __future__ import annotations import os from collections.abc import Sequence -from datetime import datetime +from datetime import datetime, timezone from typing import TYPE_CHECKING, Any from uuid import UUID @@ -74,7 +74,7 @@ class LangFuseTracer(BaseTracer): metadata: dict[str, Any] | None = None, vertex: Vertex | None = None, ): - start_time = datetime.utcnow() + start_time = datetime.now(tz=timezone.utc) if not self._ready: return @@ -103,7 +103,7 @@ class LangFuseTracer(BaseTracer): error: Exception | None = None, logs: Sequence[Log | dict] = (), ): - end_time = datetime.utcnow() + end_time = datetime.now(tz=timezone.utc) if not self._ready: return diff --git a/src/backend/base/pyproject.toml b/src/backend/base/pyproject.toml index 1a15ea8d3..b91d978ad 100644 --- a/src/backend/base/pyproject.toml +++ b/src/backend/base/pyproject.toml @@ -162,6 +162,7 @@ select = [ "C4", "COM", "DJ", + "DTZ", "E", "EM", "F",