diff --git a/src/documents/consumer.py b/src/documents/consumer.py index b47962d6e..5baed81e6 100644 --- a/src/documents/consumer.py +++ b/src/documents/consumer.py @@ -426,8 +426,8 @@ class ConsumerPlugin( ProgressStatusOptions.WORKING, ConsumerStatusShortMessage.PARSE_DATE, ) - date_parser = get_date_parser() - date = next(date_parser.parse(self.filename, text), None) + with get_date_parser() as date_parser: + date = next(date_parser.parse(self.filename, text), None) archive_path = document_parser.get_archive_path() page_count = document_parser.get_page_count(self.working_copy, mime_type) diff --git a/src/documents/plugins/date_parsing/base.py b/src/documents/plugins/date_parsing/base.py index 93e4cecaa..c6df1a70f 100644 --- a/src/documents/plugins/date_parsing/base.py +++ b/src/documents/plugins/date_parsing/base.py @@ -4,6 +4,12 @@ from abc import ABC from abc import abstractmethod from collections.abc import Iterator from dataclasses import dataclass +from types import TracebackType + +try: + from typing import Self +except ImportError: + from typing_extensions import Self import dateparser @@ -28,6 +34,7 @@ class DateParserConfig: reference_time: datetime.datetime # Settings for the default RegexDateParser + # Other plugins should use or consider these, but it is not required filename_date_order: str | None content_date_order: str @@ -45,6 +52,28 @@ class DateParserPluginBase(ABC): """ 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( self, date_string: str, diff --git a/src/documents/views.py b/src/documents/views.py index bc785f61d..00e1bf784 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -1023,17 +1023,17 @@ class DocumentViewSet( dates = [] if settings.NUMBER_OF_SUGGESTED_DATES > 0: - date_parser = get_date_parser() - gen = date_parser.parse(doc.filename, doc.content) - dates = sorted( - { - i - for i in itertools.islice( - gen, - settings.NUMBER_OF_SUGGESTED_DATES, - ) - }, - ) + with get_date_parser() as date_parser: + gen = date_parser.parse(doc.filename, doc.content) + dates = sorted( + { + i + for i in itertools.islice( + gen, + settings.NUMBER_OF_SUGGESTED_DATES, + ) + }, + ) resp_data = { "correspondents": [