Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Make the Django ORM writes timezone-aware

claude[bot]3f82afc026b6
diff --git a/docs/plans/issue-371-enable-dtz-rule.md b/docs/plans/issue-371-enable-dtz-rule.md
index 3782a7a..6f661d4 100644
--- a/docs/plans/issue-371-enable-dtz-rule.md
+++ b/docs/plans/issue-371-enable-dtz-rule.md
@@ -31,7 +31,7 @@ Do not bulk-autofix. Run `uv run ruff check --no-cache --select DTZ --statistics
end of each section and check the count has dropped by the number of sites that section
owns.
-## PR 1: Make the Django ORM writes timezone-aware
+## PR 1: Make the Django ORM writes timezone-aware (Done)
**Estimated added lines:** ~70 (4 call sites, 2 imports, ~40 lines of test)
**Files:** mwmbl/views.py, mwmbl/background.py, pyproject.toml,
test/test_domain_submissions.py, test/test_curation_timestamps.py (new)
diff --git a/mwmbl/background.py b/mwmbl/background.py
index 5a83282..e8dc6ab 100644
--- a/mwmbl/background.py
+++ b/mwmbl/background.py
@@ -81,7 +81,7 @@ def copy_all_indexes(new_index_path):
# Update the start page
old_index_info.last_page_copied = end_page
- old_index_info.last_copied_time = datetime.utcnow()
+ old_index_info.last_copied_time = datetime.now(timezone.utc)
old_index_info.save()
logger.info(f"Copied pages from {old_index_info.index_path} to {new_index_path} up to page {end_page}")
diff --git a/mwmbl/views.py b/mwmbl/views.py
index 48b78d2..12ba58f 100644
--- a/mwmbl/views.py
+++ b/mwmbl/views.py
@@ -1,6 +1,5 @@
from collections import defaultdict
from dataclasses import asdict
-from datetime import datetime
from logging import getLogger
from typing import Optional
from urllib.parse import urlencode
@@ -14,6 +13,7 @@ from django.contrib.auth.mixins import LoginRequiredMixin
from django.forms import CharField, ModelForm, RadioSelect
from django.http import HttpResponseBadRequest
from django.shortcuts import redirect, render
+from django.utils import timezone
from django.views.decorators.http import require_http_methods
from django.views.generic import DetailView, ListView
from requests.exceptions import RequestException
@@ -247,7 +247,7 @@ def submit_domain(request):
if form.is_valid():
domain_submission = form.save(commit=False)
domain_submission.submitted_by = request.user
- domain_submission.submitted_on = datetime.utcnow()
+ domain_submission.submitted_on = timezone.now()
domain_submission.save()
return redirect("domain_submissions")
else:
@@ -382,7 +382,7 @@ def _get_curation(request, query, documents, reranked_documents):
curation = Curation(
user=user,
- timestamp=datetime.utcnow(),
+ timestamp=timezone.now(),
query=query,
original_index_results=[asdict(d) for d in original_index_results],
original_results=[asdict(d) for d in documents.values()],
@@ -523,7 +523,7 @@ def flag_curation(request, curation_id):
if form.is_valid():
curation = form.save(commit=False)
curation.user = request.user
- curation.timestamp = datetime.now()
+ curation.timestamp = timezone.now()
curation.curation_id = curation_id
curation.save()
return render(request, "mwmbl/flag_curation_success.html")
diff --git a/pyproject.toml b/pyproject.toml
index 4453fc4..7c33d56 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -101,6 +101,9 @@ DJANGO_SETTINGS_MODULE = "mwmbl.settings_test"
python_files = ["tests.py", "test_*.py", "*_tests.py"]
addopts = "--reuse-db -m 'not live and not slow'"
asyncio_mode = "auto"
+# DTZ cannot see this one: at the point of assignment `timezone.now()` and
+# `datetime.utcnow()` look the same to a linter, and only Django knows the column is aware.
+filterwarnings = ["error:.*received a naive datetime:RuntimeWarning"]
markers = [
"live: hits real external endpoints; excluded from the default run. Run with -m live (used by the weekly Super Search smoke workflow).",
"slow: heavy CPU (e.g. XGBoost feature selection); excluded from the default run. Run with -m slow.",
diff --git a/test/test_curation_timestamps.py b/test/test_curation_timestamps.py
new file mode 100644
index 0000000..cd23c6a
--- /dev/null
+++ b/test/test_curation_timestamps.py
@@ -0,0 +1,64 @@
+"""
+Curation and flag timestamps must be timezone-aware: both columns are `DateTimeField`s
+and `USE_TZ` is on, so a naive value is stored as if it were local time.
+"""
+
+from datetime import timedelta
+
+import pytest
+from django.urls import reverse
+from django.utils import timezone
+
+from mwmbl.models import Curation, FlagCuration, MwmblUser
+
+
+def curator(db):
+ return MwmblUser.objects.create_user(username="curator", email="[email protected]", password="password")
+
+
+def test_approving_a_result_stores_an_aware_timestamp(client, curator):
+ client.force_login(curator)
+
+ response = client.post(
+ reverse("approve"),
+ {
+ "query": "aware timestamps",
+ "approve_url": "https://example.com/aware",
+ "url": ["https://example.com/aware"],
+ "title": ["Aware"],
+ "extract": ["An extract"],
+ "state": [""],
+ "score": ["1.0"],
+ },
+ )
+
+ assert response.status_code == 200
+ curation = Curation.objects.get()
+ assert curation.timestamp.tzinfo is not None
+ assert curation.timestamp.utcoffset() == timedelta(0)
+
+
+def test_flagging_a_curation_stores_an_aware_timestamp(client, curator):
+ curation = Curation.objects.create(
+ user=curator,
+ timestamp=timezone.now(),
+ query="aware timestamps",
+ original_index_results=[],
+ original_results=[],
+ new_results=[],
+ num_changes=1,
+ )
+ client.force_login(curator)
+
+ response = client.post(
+ reverse("flag_curation", args=[curation.id]),
+ {"flag": "RELEVANCE", "reason": "Not useful"},
+ )
+
+ assert response.status_code == 200
+ flag = FlagCuration.objects.get()
+ assert flag.timestamp.tzinfo is not None
+ assert flag.timestamp.utcoffset() == timedelta(0)
diff --git a/test/test_domain_submissions.py b/test/test_domain_submissions.py
index e8eadb7..b26a5ff 100644
--- a/test/test_domain_submissions.py
+++ b/test/test_domain_submissions.py
@@ -65,7 +65,9 @@ def test_form_stores_bare_domain(client, user):
response = client.post(reverse("submit_domain"), {"name": "https://www.idolbronze.com/"})
assert response.status_code == 302
- assert DomainSubmission.objects.get().name == "www.idolbronze.com"
+ submission = DomainSubmission.objects.get()
+ assert submission.name == "www.idolbronze.com"
+ assert submission.submitted_on.tzinfo is not None
@pytest.mark.django_db