ref: Add ruff rules for datetime (DTZ) (#4003)

Add ruff rules for datetime (DTZ)
This commit is contained in:
Christophe Bornet 2024-10-03 16:22:25 +02:00 • committed by GitHub
commit 528e676e56
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 15 additions and 15 deletions

View file

@ -1,5 +1,5 @@
import hashlib import hashlib
from datetime import datetime from datetime import datetime, timezone
from http import HTTPStatus from http import HTTPStatus
from io import BytesIO from io import BytesIO
from pathlib import Path 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") raise HTTPException(status_code=403, detail="You don't have access to this flow")
file_content = await file.read() 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() file_name = file.filename or hashlib.sha256(file_content).hexdigest()
full_file_name = f"{timestamp}_{file_name}" full_file_name = f"{timestamp}_{file_name}"
folder = flow_id_str folder = flow_id_str

View file

@ -390,7 +390,7 @@ async def download_multiple_file(
zip_stream.seek(0) zip_stream.seek(0)
# Generate the filename with the current datetime # 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" filename = f"{current_time}_langflow_flows.zip"
return StreamingResponse( return StreamingResponse(

View file

@ -390,10 +390,9 @@ def get_project_data(project):
project_is_component = project.get("is_component") project_is_component = project.get("is_component")
project_updated_at = project.get("updated_at") project_updated_at = project.get("updated_at")
if not project_updated_at: if not project_updated_at:
project_updated_at = datetime.now(tz=timezone.utc).isoformat() updated_at_datetime = datetime.now(tz=timezone.utc)
updated_at_datetime = datetime.strptime(project_updated_at, "%Y-%m-%dT%H:%M:%S.%f%z")
else: 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_data = project.get("data")
project_icon = project.get("icon") project_icon = project.get("icon")
project_icon = demojize(project_icon) if project_icon and purely_emoji(project_icon) else "" 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): if hasattr(existing, key):
# flow dict from json and db representation are not 100% the same # flow dict from json and db representation are not 100% the same
setattr(existing, key, value) setattr(existing, key, value)
existing.updated_at = datetime.utcnow() existing.updated_at = datetime.now(tz=timezone.utc).astimezone()
existing.user_id = user_id existing.user_id = user_id
session.add(existing) session.add(existing)
else: else:
logger.info(f"Creating new flow: {flow_id} with endpoint name {flow_endpoint_name}") logger.info(f"Creating new flow: {flow_id} with endpoint name {flow_endpoint_name}")
flow["user_id"] = user_id flow["user_id"] = user_id
flow = Flow.model_validate(flow, from_attributes=True) 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) session.add(flow)

View file

@ -29,7 +29,7 @@ def _timestamp_to_str(timestamp: datetime | str) -> str:
if isinstance(timestamp, str): if isinstance(timestamp, str):
# Just check if the string is a valid datetime # Just check if the string is a valid datetime
try: try:
datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") # noqa: DTZ007
return timestamp return timestamp
except ValueError as e: except ValueError as e:
msg = f"Invalid timestamp: {timestamp}" msg = f"Invalid timestamp: {timestamp}"

View file

@ -2,7 +2,7 @@ from __future__ import annotations
import time import time
from contextlib import contextmanager from contextlib import contextmanager
from datetime import datetime from datetime import datetime, timezone
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
@ -206,7 +206,7 @@ class DatabaseService(Service):
logger.info(f"Running DB migrations in {self.script_location}") logger.info(f"Running DB migrations in {self.script_location}")
try: 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) command.check(alembic_cfg)
except Exception as exc: except Exception as exc:
if isinstance(exc, util.exc.CommandError | util.exc.AutogenerateDiffsDetected): if isinstance(exc, util.exc.CommandError | util.exc.AutogenerateDiffsDetected):
@ -214,7 +214,7 @@ class DatabaseService(Service):
time.sleep(3) time.sleep(3)
try: 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) command.check(alembic_cfg)
except util.exc.AutogenerateDiffsDetected as exc: except util.exc.AutogenerateDiffsDetected as exc:
logger.error(f"AutogenerateDiffsDetected: {exc}") logger.error(f"AutogenerateDiffsDetected: {exc}")

View file

@ -2,7 +2,7 @@ from __future__ import annotations
import os import os
from collections.abc import Sequence from collections.abc import Sequence
from datetime import datetime from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from uuid import UUID from uuid import UUID
@ -74,7 +74,7 @@ class LangFuseTracer(BaseTracer):
metadata: dict[str, Any] | None = None, metadata: dict[str, Any] | None = None,
vertex: Vertex | None = None, vertex: Vertex | None = None,
): ):
start_time = datetime.utcnow() start_time = datetime.now(tz=timezone.utc)
if not self._ready: if not self._ready:
return return
@ -103,7 +103,7 @@ class LangFuseTracer(BaseTracer):
error: Exception | None = None, error: Exception | None = None,
logs: Sequence[Log | dict] = (), logs: Sequence[Log | dict] = (),
): ):
end_time = datetime.utcnow() end_time = datetime.now(tz=timezone.utc)
if not self._ready: if not self._ready:
return return

View file

@ -162,6 +162,7 @@ select = [
"C4", "C4",
"COM", "COM",
"DJ", "DJ",
"DTZ",
"E", "E",
"EM", "EM",
"F", "F",