Skip to content

Commit 8ef6231

Browse files
replace deprecated datetime.utc* calls
use 100% compatible helper functions: - moin.util.utcfromtimestamp - moin.util.utcnow locustfile: didn't want to import stuff from moin there, thus replaced the code there locally.
1 parent a2b0abd commit 8ef6231

File tree

10 files changed

+42
-31
lines changed

10 files changed

+42
-31
lines changed

.pre-commit-config.yaml

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
repos:
2-
- repo: https://github.com/psf/black
3-
rev: 24.3.0
4-
hooks:
5-
- id: black
6-
- repo: https://github.com/pycqa/flake8
7-
rev: 6.1.0
8-
hooks:
9-
- id: flake8
10-
files: '(src|_ui_tests|contrib|scripts|quickinstall.py)'
2+
- repo: https://github.com/psf/black
3+
rev: 24.3.0
4+
hooks:
5+
- id: black
6+
- repo: https://github.com/astral-sh/ruff-pre-commit
7+
rev: v0.3.5
8+
hooks:
9+
- id: ruff

contrib/loadtesting/locust/locustfile.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import sys
55
import argparse
66
import urllib.request, urllib.error, urllib.parse
7-
from datetime import datetime
7+
from datetime import datetime, timezone
88
from time import time
99

1010
from locust import HttpLocust, Locust, TaskSet, HttpUser, task, SequentialTaskSet, between, User, events
@@ -360,4 +360,4 @@ def logout(self):
360360
print("%s: response.status_code = %s" % (sys._getframe().f_lineno, response.status_code))
361361

362362
def get_time(self):
363-
return datetime.utcfromtimestamp(time()).isoformat()[:-7].replace("T", " ")
363+
return datetime.fromtimestamp(time(), tz=timezone.utc).isoformat()[:19].replace("T", " ")

src/moin/apps/frontend/views.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@
9696
from moin.constants.itemtypes import ITEMTYPE_DEFAULT, ITEMTYPE_TICKET
9797
from moin.constants.contenttypes import * # noqa
9898
from moin.constants.rights import SUPERUSER
99-
from moin.utils import crypto, rev_navigation, close_file, show_time
99+
from moin.utils import crypto, rev_navigation, close_file, show_time, utcfromtimestamp
100100
from moin.utils.crypto import make_uuid, hash_hexdigest
101101
from moin.utils.interwiki import url_for_item, split_fqname, CompositeName
102102
from moin.utils.mime import Type, type_moin_document
@@ -1159,9 +1159,9 @@ def log_destroy_action(item, subitem_names, comment, revision=None):
11591159
(" Old Name", item.meta[NAME_OLD]),
11601160
(" Subitem Names", subitem_names),
11611161
(" Namespace", item.meta[NAMESPACE]),
1162-
(" Last Modified Time", format_datetime(datetime.utcfromtimestamp(item.meta[MTIME]))),
1162+
(" Last Modified Time", format_datetime(utcfromtimestamp(item.meta[MTIME]))),
11631163
(" Last Modified By", item.meta[ADDRESS]),
1164-
(" Destroyed Time", format_datetime(datetime.utcfromtimestamp(time.time()))),
1164+
(" Destroyed Time", format_datetime(utcfromtimestamp(time.time()))),
11651165
(" Destroyed By", flaskg.user.name),
11661166
(" Content Type", item.meta[CONTENTTYPE]),
11671167
(" Revision Number", item.meta[REV_NUMBER]),
@@ -1633,7 +1633,7 @@ def history(item_name):
16331633
terms = [Term(WIKINAME, app.cfg.interwikiname)]
16341634
terms.extend(Term(term, value) for term, value in fqname.query.items())
16351635
if bookmark_time:
1636-
terms.append(DateRange(MTIME, start=datetime.utcfromtimestamp(bookmark_time), end=None))
1636+
terms.append(DateRange(MTIME, start=utcfromtimestamp(bookmark_time), end=None))
16371637
query = And(terms)
16381638

16391639
if results_per_page:
@@ -1722,7 +1722,7 @@ def global_history(namespace):
17221722
terms.append(Not(Term(NAMESPACE, NAMESPACE_USERPROFILES)))
17231723
bookmark_time = flaskg.user.bookmark
17241724
if bookmark_time is not None:
1725-
terms.append(DateRange(MTIME, start=datetime.utcfromtimestamp(bookmark_time), end=None))
1725+
terms.append(DateRange(MTIME, start=utcfromtimestamp(bookmark_time), end=None))
17261726
query = And(terms)
17271727

17281728
if results_per_page:

src/moin/converters/archive_in.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from ._table import TableMixin
1717

1818
from moin.i18n import _
19+
from moin.utils import utcfromtimestamp
1920
from moin.utils.iri import Iri
2021
from moin.utils.tree import moin_page, xlink
2122
from moin.utils.mime import Type, type_moin_document
@@ -98,7 +99,7 @@ def list_contents(self, fileobj):
9899
for tinfo in tf.getmembers():
99100
if tinfo.isfile():
100101
# display only normal files, not directories
101-
rows.append((tinfo.size, datetime.utcfromtimestamp(tinfo.mtime), tinfo.name))
102+
rows.append((tinfo.size, utcfromtimestamp(tinfo.mtime), tinfo.name))
102103
return rows
103104
except tarfile.TarError as err:
104105
raise ArchiveException(str(err))

src/moin/forms.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
from moin.constants.keys import ITEMID, NAME, LATEST_REVS, NAMESPACE, FQNAME
6161
from moin.constants.namespaces import NAMESPACES_IDENTIFIER
6262
from moin.i18n import _, L_
63+
from moin.utils import utcfromtimestamp
6364
from moin.utils.forms import FileStorage
6465
from moin.storage.middleware.validation import uuid_validator
6566

@@ -363,7 +364,7 @@ def serialize(self, value):
363364
"""Serializes value to string."""
364365
if isinstance(value, int):
365366
try:
366-
value = datetime.datetime.utcfromtimestamp(value)
367+
value = utcfromtimestamp(value)
367368
except ValueError:
368369
pass
369370
return super().serialize(value)
@@ -377,7 +378,7 @@ def adapt(self, value):
377378
if isinstance(value, int):
378379
try:
379380
# check if a value is a correct timestamp
380-
dt = datetime.datetime.utcfromtimestamp(value)
381+
dt = utcfromtimestamp(value)
381382
return value
382383
except (ValueError, OSError): # OSError errno 75 "Value too large for defined data type"
383384
raise AdaptationError()

src/moin/macros/_tests/test_Date.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77
"""
88

99
import time
10-
from datetime import datetime
1110

1211
import pytest
1312
from flask import g as flaskg
1413

1514
from moin.macros.Date import MacroDateTimeBase, Macro
15+
from moin.utils import utcfromtimestamp
1616
from moin.utils.show_time import format_date_time, format_date
1717

1818

@@ -24,12 +24,12 @@ def test_parse_time(self):
2424
expected = 1691386691.0
2525
assert ts == expected
2626

27-
result = format_date_time(datetime.utcfromtimestamp(ts))
27+
result = format_date_time(utcfromtimestamp(ts))
2828
expected = "2023-08-07 05:38:11z"
2929
assert result == expected
3030

3131
flaskg.user.valid = True # show_time creates ISO 8601 dates if user is not logged in
32-
result = format_date_time(datetime.utcfromtimestamp(ts))
32+
result = format_date_time(utcfromtimestamp(ts))
3333
expected = ["Aug 7, 2023, 5:38:11\u202fAM", "Aug 7, 2023, 5:38:11 AM"] # TODO: remove 2nd entry later
3434
assert result in expected
3535

@@ -49,7 +49,7 @@ def test_macro(self):
4949
# when arguments is None
5050
result = macro_obj.macro("content", None, "page_url", "alternative")
5151
test_time = time.time()
52-
test_time = format_date(datetime.utcfromtimestamp(test_time))
52+
test_time = format_date(utcfromtimestamp(test_time))
5353
assert result == test_time
5454

5555
arguments = ["2023-08-07T11:11:11+0533", "argument2"]

src/moin/macros/_tests/test_DateTime.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@
77
"""
88

99
import time
10-
from datetime import datetime
1110

1211
from flask import g as flaskg
1312

1413
import pytest
1514

1615
from moin.macros.DateTime import Macro
16+
from moin.utils import utcfromtimestamp
1717
from moin.utils.show_time import format_date_time
1818

1919

@@ -26,7 +26,7 @@ def test_Macro():
2626
# get the current time
2727
test_time = time.time()
2828
test_times = [test_time, test_time - 1] # in case our call to time.time happened just after the second rolled over
29-
test_times = [format_date_time(datetime.utcfromtimestamp(t)) for t in test_times]
29+
test_times = [format_date_time(utcfromtimestamp(t)) for t in test_times]
3030
assert result in test_times
3131

3232
arguments = ["2023-08-07T11:11:11", "argument2"]

src/moin/storage/middleware/indexing.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,6 @@
5252
import os
5353
import sys
5454
import shutil
55-
import datetime
5655
import time
5756

5857
from collections.abc import Mapping
@@ -76,8 +75,8 @@
7675
from moin.themes import utctimestamp
7776
from moin.storage.middleware.validation import ContentMetaSchema, UserMetaSchema, validate_data
7877
from moin.storage.error import NoSuchItemError, ItemAlreadyExistsError
78+
from moin.utils import utcfromtimestamp
7979
from moin.utils.interwiki import split_fqname, CompositeName
80-
8180
from moin.utils.mime import Type, type_moin_document
8281
from moin.utils.tree import moin_page
8382
from moin.converters import default_registry
@@ -173,7 +172,7 @@ def backend_to_index(meta, content, schema, wikiname, backend_name):
173172
for key in [MTIME, PTIME]:
174173
if key in doc:
175174
# we have UNIX UTC timestamp (int), whoosh wants datetime
176-
doc[key] = datetime.datetime.utcfromtimestamp(doc[key])
175+
doc[key] = utcfromtimestamp(doc[key])
177176
doc[NAME_EXACT] = doc[NAME]
178177
doc[WIKINAME] = wikiname
179178
doc[CONTENT] = content

src/moin/utils/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
"""
88

99

10+
from datetime import datetime, timezone
1011
import re
1112
import pickle
1213
from io import BytesIO
@@ -86,3 +87,13 @@ def close_file(f):
8687
# some tests reuse BytesIO objects and will fail with I/O operation on closed file.
8788
if hasattr(f, "close") and not f.closed and not isinstance(f, BytesIO):
8889
f.close()
90+
91+
92+
def utcfromtimestamp(timestamp):
93+
"""Returns a naive datetime instance representing the timestamp in the UTC timezone"""
94+
return datetime.fromtimestamp(timestamp, timezone.utc).replace(tzinfo=None)
95+
96+
97+
def utcnow():
98+
"""Returns a naive datetime instance representing the current time in the UTC timezone"""
99+
return datetime.now(timezone.utc).replace(tzinfo=None)

src/moin/utils/show_time.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
# Copyright: 2019 MoinMoin:RogerHaase
22
# License: GNU GPL v2 (or any later version), see LICENSE.txt for details.
33

4-
import datetime
54
import pytz
65

76
from flask import g as flaskg
87
import flask_babel
98

109
from moin.i18n import _
1110
from moin import i18n
11+
from moin.utils import utcfromtimestamp, utcnow
1212

1313

1414
def duration(seconds):
@@ -52,9 +52,9 @@ def format_date_time(utc_dt=None, fmt="yyyy-MM-dd HH:mm:ss", interval="datetime"
5252
See https://babel.pocoo.org/en/latest/dates.html#date-fields for babel format syntax.
5353
"""
5454
if utc_dt is None:
55-
utc_dt = datetime.datetime.utcnow()
55+
utc_dt = utcnow()
5656
elif isinstance(utc_dt, (float, int)):
57-
utc_dt = datetime.datetime.utcfromtimestamp(utc_dt)
57+
utc_dt = utcfromtimestamp(utc_dt)
5858

5959
if not flaskg.user.valid:
6060
# users who are not logged-in get moin version of ISO 8601: 2019-07-15 07:08:09z

0 commit comments

Comments
 (0)