To enable cleanup, use as a context manager

This commit is contained in:
Trenton H
2026-01-28 15:45:27 -08:00
parent a055de0ce4
commit 7704bc5399
3 changed files with 42 additions and 13 deletions

View File

@@ -426,8 +426,8 @@ class ConsumerPlugin(
ProgressStatusOptions.WORKING, ProgressStatusOptions.WORKING,
ConsumerStatusShortMessage.PARSE_DATE, ConsumerStatusShortMessage.PARSE_DATE,
) )
date_parser = get_date_parser() with get_date_parser() as date_parser:
date = next(date_parser.parse(self.filename, text), None) date = next(date_parser.parse(self.filename, text), None)
archive_path = document_parser.get_archive_path() archive_path = document_parser.get_archive_path()
page_count = document_parser.get_page_count(self.working_copy, mime_type) page_count = document_parser.get_page_count(self.working_copy, mime_type)

View File

@@ -4,6 +4,12 @@ from abc import ABC
from abc import abstractmethod from abc import abstractmethod
from collections.abc import Iterator from collections.abc import Iterator
from dataclasses import dataclass from dataclasses import dataclass
from types import TracebackType
try:
from typing import Self
except ImportError:
from typing_extensions import Self
import dateparser import dateparser
@@ -28,6 +34,7 @@ class DateParserConfig:
reference_time: datetime.datetime reference_time: datetime.datetime
# Settings for the default RegexDateParser # Settings for the default RegexDateParser
# Other plugins should use or consider these, but it is not required
filename_date_order: str | None filename_date_order: str | None
content_date_order: str content_date_order: str
@@ -45,6 +52,28 @@ class DateParserPluginBase(ABC):
""" """
self.config = config self.config = config
def __enter__(self) -> Self:
"""
Enter the runtime context related to this object.
Subclasses can override this to acquire resources (connections, handles).
"""
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
"""
Exit the runtime context related to this object.
Subclasses can override this to release resources.
"""
# Default implementation does nothing.
# Returning None implies exceptions are propagated.
def _parse_string( def _parse_string(
self, self,
date_string: str, date_string: str,

View File

@@ -1023,17 +1023,17 @@ class DocumentViewSet(
dates = [] dates = []
if settings.NUMBER_OF_SUGGESTED_DATES > 0: if settings.NUMBER_OF_SUGGESTED_DATES > 0:
date_parser = get_date_parser() with get_date_parser() as date_parser:
gen = date_parser.parse(doc.filename, doc.content) gen = date_parser.parse(doc.filename, doc.content)
dates = sorted( dates = sorted(
{ {
i i
for i in itertools.islice( for i in itertools.islice(
gen, gen,
settings.NUMBER_OF_SUGGESTED_DATES, settings.NUMBER_OF_SUGGESTED_DATES,
) )
}, },
) )
resp_data = { resp_data = {
"correspondents": [ "correspondents": [