Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove dependency on pytz #8984

Merged
merged 3 commits into from
Jun 4, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 5 additions & 9 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
from django.utils.formats import localize_input, sanitize_separators
from django.utils.ipv6 import clean_ipv6_address
from django.utils.translation import gettext_lazy as _
from pytz.exceptions import InvalidTimeError

from rest_framework import ISO_8601
from rest_framework.exceptions import ErrorDetail, ValidationError
Expand Down Expand Up @@ -1162,15 +1161,12 @@ def enforce_timezone(self, value):
return value.astimezone(field_timezone)
except OverflowError:
self.fail('overflow')
try:
dt = timezone.make_aware(value, field_timezone)
# When the resulting datetime is a ZoneInfo instance, it won't necessarily
# throw given an invalid datetime, so we need to specifically check.
if not valid_datetime(dt):
self.fail('make_aware', timezone=field_timezone)
return dt
except InvalidTimeError:
dt = timezone.make_aware(value, field_timezone)
Copy link
Contributor

@max-muoto max-muoto May 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should move this back to a try catch, and check that the exception's name using type(e).__name__, confirming it's equal to "InvalidTimeError". This way, we can still be specific, while removing the pytz dependency.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

excellent idea

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hum, actually it only uses derived classes of InvalidTimeError. Should we iterate over the inheritance chain (__mro__) ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I came out with something I find pretty good. The things I am annoyed with is: since we support both presence and absence of pytz in tests, the CI should test both and I doubt it does (and I yet don't see how without rerunning the test suite in a virtualenv with a different install)

# When the resulting datetime is a ZoneInfo instance, it won't necessarily
# throw given an invalid datetime, so we need to specifically check.
if not valid_datetime(dt):
self.fail('make_aware', timezone=field_timezone)
return dt
elif (field_timezone is None) and timezone.is_aware(value):
return timezone.make_naive(value, datetime.timezone.utc)
return value
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def get_version(package):
author_email='[email protected]', # SEE NOTE BELOW (*)
packages=find_packages(exclude=['tests*']),
include_package_data=True,
install_requires=["django>=3.0", "pytz", 'backports.zoneinfo;python_version<"3.9"'],
install_requires=["django>=3.0", 'backports.zoneinfo;python_version<"3.9"'],
python_requires=">=3.6",
zip_safe=False,
classifiers=[
Expand Down
26 changes: 0 additions & 26 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from unittest.mock import patch

import pytest
import pytz
from django.core.exceptions import ValidationError as DjangoValidationError
from django.db.models import IntegerChoices, TextChoices
from django.http import QueryDict
Expand Down Expand Up @@ -1590,31 +1589,6 @@ def test_should_render_date_time_in_default_timezone(self):
assert rendered_date == rendered_date_in_timezone


@pytest.mark.skipif(pytz is None, reason="As Django 4.0 has deprecated pytz, this test should eventually be able to get removed.")
class TestPytzNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
"""
Invalid values for `DateTimeField` with datetime in DST shift (non-existing or ambiguous) and timezone with DST.
Timezone America/New_York has DST shift from 2017-03-12T02:00:00 to 2017-03-12T03:00:00 and
from 2017-11-05T02:00:00 to 2017-11-05T01:00:00 in 2017.
"""
valid_inputs = {}
invalid_inputs = {
'2017-03-12T02:30:00': ['Invalid datetime for the timezone "America/New_York".'],
'2017-11-05T01:30:00': ['Invalid datetime for the timezone "America/New_York".']
}
outputs = {}

class MockTimezone(pytz.BaseTzInfo):
@staticmethod
def localize(value, is_dst):
raise pytz.InvalidTimeError()

def __str__(self):
return 'America/New_York'

field = serializers.DateTimeField(default_timezone=MockTimezone())


@patch('rest_framework.utils.timezone.datetime_ambiguous', return_value=True)
class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
"""
Expand Down