Handle some deprecations
authorRadek Czajka <radekczajka@wolnelektury.pl>
Sat, 28 Nov 2026 23:06:48 +0000 (00:06 +0100)
committerRadek Czajka <radekczajka@wolnelektury.pl>
Sat, 28 Nov 2026 23:06:48 +0000 (00:06 +0100)
Makefile
docker-compose.yml
src/catalogue/wikimedia.py
src/cover/forms.py
src/cover/models.py
src/cover/tests.py
src/cover/utils.py
src/documents/migrations/0001_initial.py
src/dvcs/models.py
src/redakcja/settings/__init__.py
src/wiki/views.py

index 247a24d..2b3de6e 100644 (file)
--- a/Makefile
+++ b/Makefile
@@ -27,13 +27,13 @@ test:
 
 .ONESHELL:
 test_full:
 
 .ONESHELL:
 test_full:
-       cd src
-       coverage run --branch --source='.' ./manage.py test --settings=redakcja.settings.test_full; true
-       coverage html -d ../htmlcov.new
-       rm -rf ../htmlcov
-       mv ../htmlcov.new ../htmlcov
-       coverage report
-       rm .coverage
+       mkdir -p htmlcov
+       UID=$(UID) GID=$(GID) $(TEST_COMPOSE) run --rm --build test sh -c '\
+         python -Wall -m coverage run --branch --source=. \
+           ./manage.py test --settings=redakcja.settings.test_full $(ARGS); s=$$?; \
+         coverage report --skip-covered; coverage html -d /app/htmlcov; exit $$s'; \
+       status=$$?; $(TEST_COMPOSE) down; exit $$status
+
 
 
 shell:
 
 
 shell:
index 9df7de7..bd1273f 100644 (file)
@@ -28,7 +28,7 @@ services:
     <<: *app-base
     ports:
      - "8001:8000"
     <<: *app-base
     ports:
      - "8001:8000"
-    command: ./manage.py runserver 0.0.0.0:8000
+    command: python -Wall ./manage.py runserver 0.0.0.0:8000
 
   db:
     image: postgres:18
 
   db:
     image: postgres:18
index fe6b1c6..657978e 100644 (file)
@@ -1,6 +1,7 @@
 from urllib.parse import unquote
 from urllib.parse import unquote
+from urllib.request import urlopen
 from django.core.files.base import ContentFile
 from django.core.files.base import ContentFile
-from cover.utils import get_wikimedia_data, URLOpener
+from cover.utils import get_wikimedia_data
 
 
 class WikiMedia:
 
 
 class WikiMedia:
@@ -70,7 +71,7 @@ class Downloadable:
         self.url = url
 
     def apply_to_field(self, obj, attname):
         self.url = url
 
     def apply_to_field(self, obj, attname):
-        t = URLOpener().open(self.url).read()
+        t = urlopen(self.url).read()
         getattr(obj, attname).save(
             unquote(self.url.rsplit('/', 1)[-1]),
             ContentFile(t),
         getattr(obj, attname).save(
             unquote(self.url.rsplit('/', 1)[-1]),
             ContentFile(t),
index a1ba182..b7fddfb 100644 (file)
@@ -2,7 +2,7 @@
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
 from io import BytesIO
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
 from io import BytesIO
-
+from urllib.request import urlopen
 from django import forms
 from django.conf import settings
 from django.utils.translation import gettext_lazy as _, gettext
 from django import forms
 from django.conf import settings
 from django.utils.translation import gettext_lazy as _, gettext
@@ -10,7 +10,7 @@ from cover.models import Image
 from django.utils.safestring import mark_safe
 from PIL import Image as PILImage
 
 from django.utils.safestring import mark_safe
 from PIL import Image as PILImage
 
-from cover.utils import get_import_data, FlickrError, URLOpener
+from cover.utils import get_import_data, FlickrError
 
 
 class ImageAddForm(forms.ModelForm):
 
 
 class ImageAddForm(forms.ModelForm):
@@ -62,7 +62,8 @@ class ImageAddForm(forms.ModelForm):
         if not download_url and not uploaded_file:
             raise forms.ValidationError(gettext('No image specified'))
         if download_url:
         if not download_url and not uploaded_file:
             raise forms.ValidationError(gettext('No image specified'))
         if download_url:
-            image_data = URLOpener().open(download_url).read()
+            with urlopen(download_url) as f:
+                image_data = f.read()
             width, height = PILImage.open(BytesIO(image_data)).size
         else:
             width, height = PILImage.open(uploaded_file.file).size
             width, height = PILImage.open(BytesIO(image_data)).size
         else:
             width, height = PILImage.open(uploaded_file.file).size
index 2c452a2..991cb95 100644 (file)
@@ -2,6 +2,7 @@
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
 from io import BytesIO
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
 from io import BytesIO
+from urllib.request import urlopen
 from django.core.files.base import ContentFile
 from django.core.files.storage import FileSystemStorage
 from django.db import models
 from django.core.files.base import ContentFile
 from django.core.files.storage import FileSystemStorage
 from django.db import models
@@ -14,7 +15,6 @@ from PIL import Image as PILImage
 from librarian.dcparser import BookInfo
 from librarian.meta.types.person import Person
 from librarian.cover import make_cover
 from librarian.dcparser import BookInfo
 from librarian.meta.types.person import Person
 from librarian.cover import make_cover
-from cover.utils import URLOpener
 
 
 class OverwriteStorage(FileSystemStorage):
 
 
 class OverwriteStorage(FileSystemStorage):
@@ -152,5 +152,5 @@ class Image(models.Model):
 @receiver(post_save, sender=Image)
 def download_image(sender, instance, **kwargs):
     if instance.pk and not instance.file:
 @receiver(post_save, sender=Image)
 def download_image(sender, instance, **kwargs):
     if instance.pk and not instance.file:
-        t = URLOpener().open(instance.download_url).read()
+        t = urlopen(instance.download_url).read()
         instance.file.save("%d.jpg" % instance.pk, ContentFile(t))
         instance.file.save("%d.jpg" % instance.pk, ContentFile(t))
index 910b0df..558cd03 100644 (file)
@@ -57,7 +57,7 @@ class FlickrTests(TestCase):
                 'title': 'Valdai IverskyMon asv2018 img47',
                 'author': 'A.Savin',
                 'source_url': 'https://commons.wikimedia.org/wiki/File:Valdai_IverskyMon_asv2018_img47.jpg',
                 'title': 'Valdai IverskyMon asv2018 img47',
                 'author': 'A.Savin',
                 'source_url': 'https://commons.wikimedia.org/wiki/File:Valdai_IverskyMon_asv2018_img47.jpg',
-                'download_url': 'https://upload.wikimedia.org/wikipedia/commons/4/43/Valdai_IverskyMon_asv2018_img47.jpg',
+                'download_url': 'https://upload.wikimedia.org/wikipedia/commons/4/43/Valdai_IverskyMon_asv2018_img47.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=original',
                 'license_url': 'http://artlibre.org/licence/lal/en',
                 'license_name': 'FAL'
             }
                 'license_url': 'http://artlibre.org/licence/lal/en',
                 'license_name': 'FAL'
             }
@@ -74,7 +74,7 @@ class FlickrTests(TestCase):
                 'title': 'Chłopiec w słomkowym kapeluszu',
                 'author': 'Mykoła Pymonenko',
                 'source_url': 'https://commons.wikimedia.org/wiki/File:Pymonenko_A_boy_in_a_straw_hat.jpg',
                 'title': 'Chłopiec w słomkowym kapeluszu',
                 'author': 'Mykoła Pymonenko',
                 'source_url': 'https://commons.wikimedia.org/wiki/File:Pymonenko_A_boy_in_a_straw_hat.jpg',
-                'download_url': 'https://upload.wikimedia.org/wikipedia/commons/9/9b/Pymonenko_A_boy_in_a_straw_hat.jpg',
+                'download_url': 'https://upload.wikimedia.org/wikipedia/commons/9/9b/Pymonenko_A_boy_in_a_straw_hat.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=original',
                 'license_url': 'https://pl.wikipedia.org/wiki/Domena_publiczna',
                 'license_name': 'domena publiczna'
             }
                 'license_url': 'https://pl.wikipedia.org/wiki/Domena_publiczna',
                 'license_name': 'domena publiczna'
             }
index 59e194f..8440e06 100644 (file)
@@ -5,17 +5,16 @@ import csv
 from io import StringIO
 import json
 import re
 from io import StringIO
 import json
 import re
-from urllib.request import FancyURLopener
+from urllib.request import build_opener, install_opener, urlopen
 from django.conf import settings
 import requests
 from wikidata.client import Client
 from catalogue.constants import WIKIDATA
 
 
 from django.conf import settings
 import requests
 from wikidata.client import Client
 from catalogue.constants import WIKIDATA
 
 
-class URLOpener(FancyURLopener):
-    @property
-    def version(self):
-        return 'FNP Redakcja'
+opener = build_opener()
+opener.addheaders = [("User-Agent", "WolneLektury-Redakcja/1.0 (fundacja@wolnelektury.pl)")]
+install_opener(opener)
 
 
 class FlickrError(Exception):
 
 
 class FlickrError(Exception):
@@ -29,7 +28,7 @@ def get_flickr_data(url):
     author_slug, img_id = m.group('author'), m.group('img')
     base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
     try:
     author_slug, img_id = m.group('author'), m.group('img')
     base_url = "https://www.flickr.com/photos/%s/%s/" % (author_slug, img_id)
     try:
-        html = URLOpener().open(url).read().decode('utf-8')
+        html = urlopen(url).read().decode('utf-8')
     except IOError:
         raise FlickrError('Error reading page')
     match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
     except IOError:
         raise FlickrError('Error reading page')
     match = re.search(r'<a href="([^"]*)"[^>]* rel="license ', html)
@@ -77,7 +76,7 @@ def get_flickr_data(url):
 
 def get_wikimedia_data(url):
     file_name = url.rsplit('/', 1)[-1].rsplit(':', 1)[-1]
 
 def get_wikimedia_data(url):
     file_name = url.rsplit('/', 1)[-1].rsplit(':', 1)[-1]
-    d = json.loads(URLOpener().open('https://commons.wikimedia.org/w/api.php?action=query&titles=File:{}&prop=imageinfo&iiprop=url|user|extmetadata&iimetadataversion=latest&format=json'.format(file_name)).read().decode('utf-8'))
+    d = json.loads(urlopen('https://commons.wikimedia.org/w/api.php?action=query&titles=File:{}&prop=imageinfo&iiprop=url|user|extmetadata&iimetadataversion=latest&format=json'.format(file_name)).read().decode('utf-8'))
 
     d = list(d['query']['pages'].values())[0]['imageinfo'][0]
     ext = d['extmetadata']
 
     d = list(d['query']['pages'].values())[0]['imageinfo'][0]
     ext = d['extmetadata']
@@ -120,7 +119,7 @@ def get_mnw_data(url):
     d = list(
         csv.DictReader(
             StringIO(
     d = list(
         csv.DictReader(
             StringIO(
-                URLOpener().open(
+                urlopen(
                     'https://cyfrowe-api.mnw.art.pl/api/object/{}/csv'.format(nr)
                 ).read().decode('utf-8')
             )
                     'https://cyfrowe-api.mnw.art.pl/api/object/{}/csv'.format(nr)
                 ).read().decode('utf-8')
             )
index 451029b..a4d6fc2 100644 (file)
@@ -8,12 +8,12 @@ is made to remove previous `catalogue` migrations, this will need
 to be converted to a real database migration.
 """
 
 to be converted to a real database migration.
 """
 
-import datetime
 from django.conf import settings
 import django.contrib.auth.models
 import django.core.files.storage
 from django.db import migrations, models
 import django.db.models.deletion
 from django.conf import settings
 import django.contrib.auth.models
 import django.core.files.storage
 from django.db import migrations, models
 import django.db.models.deletion
+import django.utils.timezone
 import dvcs.models
 
 
 import dvcs.models
 
 
@@ -98,7 +98,7 @@ class Migration(migrations.Migration):
                 ('author_email', models.CharField(blank=True, help_text='Used if author is not set.', max_length=128, null=True, verbose_name='author email')),
                 ('revision', models.IntegerField(db_index=True, verbose_name='revision')),
                 ('description', models.TextField(blank=True, default='', verbose_name='description')),
                 ('author_email', models.CharField(blank=True, help_text='Used if author is not set.', max_length=128, null=True, verbose_name='author email')),
                 ('revision', models.IntegerField(db_index=True, verbose_name='revision')),
                 ('description', models.TextField(blank=True, default='', verbose_name='description')),
-                ('created_at', models.DateTimeField(db_index=True, default=datetime.datetime.now, editable=False)),
+                ('created_at', models.DateTimeField(db_index=True, default=django.utils.timezone.now, editable=False)),
                 ('publishable', models.BooleanField(default=False, verbose_name='publishable')),
                 ('data', models.FileField(storage=django.core.files.storage.FileSystemStorage(location=settings.CATALOGUE_REPO_PATH), upload_to=dvcs.models.data_upload_to, verbose_name='data')),
                 ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='author')),
                 ('publishable', models.BooleanField(default=False, verbose_name='publishable')),
                 ('data', models.FileField(storage=django.core.files.storage.FileSystemStorage(location=settings.CATALOGUE_REPO_PATH), upload_to=dvcs.models.data_upload_to, verbose_name='data')),
                 ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='author')),
@@ -158,7 +158,7 @@ class Migration(migrations.Migration):
                 ('author_email', models.CharField(blank=True, help_text='Used if author is not set.', max_length=128, null=True, verbose_name='author email')),
                 ('revision', models.IntegerField(db_index=True, verbose_name='revision')),
                 ('description', models.TextField(blank=True, default='', verbose_name='description')),
                 ('author_email', models.CharField(blank=True, help_text='Used if author is not set.', max_length=128, null=True, verbose_name='author email')),
                 ('revision', models.IntegerField(db_index=True, verbose_name='revision')),
                 ('description', models.TextField(blank=True, default='', verbose_name='description')),
-                ('created_at', models.DateTimeField(db_index=True, default=datetime.datetime.now, editable=False)),
+                ('created_at', models.DateTimeField(db_index=True, default=django.utils.timezone.now, editable=False)),
                 ('publishable', models.BooleanField(default=False, verbose_name='publishable')),
                 ('data', models.FileField(storage=django.core.files.storage.FileSystemStorage(location=settings.CATALOGUE_IMAGE_REPO_PATH), upload_to=dvcs.models.data_upload_to, verbose_name='data')),
                 ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='author')),
                 ('publishable', models.BooleanField(default=False, verbose_name='publishable')),
                 ('data', models.FileField(storage=django.core.files.storage.FileSystemStorage(location=settings.CATALOGUE_IMAGE_REPO_PATH), upload_to=dvcs.models.data_upload_to, verbose_name='data')),
                 ('author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='author')),
index 5d7d7ff..cc54329 100644 (file)
@@ -1,7 +1,6 @@
 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 #
-from datetime import datetime
 import os.path
 from zlib import compress, decompress
 
 import os.path
 from zlib import compress, decompress
 
@@ -11,6 +10,7 @@ from django.core.files.storage import FileSystemStorage
 from django.db import models, transaction
 from django.db.models.base import ModelBase
 from django.utils.text import format_lazy
 from django.db import models, transaction
 from django.db.models.base import ModelBase
 from django.utils.text import format_lazy
+from django.utils.timezone import now
 from django.utils.translation import gettext_lazy as _
 import merge3
 
 from django.utils.translation import gettext_lazy as _
 import merge3
 
@@ -85,7 +85,7 @@ class Change(models.Model):
         'self', models.SET_NULL, null=True, blank=True, default=None, verbose_name=_('merge parent'), related_name="merge_children")
 
     description = models.TextField(_('description'), blank=True, default='')
         'self', models.SET_NULL, null=True, blank=True, default=None, verbose_name=_('merge parent'), related_name="merge_children")
 
     description = models.TextField(_('description'), blank=True, default='')
-    created_at = models.DateTimeField(editable=False, db_index=True, default=datetime.now)
+    created_at = models.DateTimeField(editable=False, db_index=True, default=now)
     publishable = models.BooleanField(_('approved'), default=False)
 
     class Meta:
     publishable = models.BooleanField(_('approved'), default=False)
 
     class Meta:
index 299637b..bdcb8a2 100644 (file)
@@ -313,6 +313,8 @@ LANGUAGES = [
 ]
 
 
 ]
 
 
+USE_TZ = True
+
 TEST_INTEGRATION = False
 
 
 TEST_INTEGRATION = False
 
 
index 3e6fedb..275a08b 100644 (file)
@@ -16,6 +16,7 @@ from django.http import Http404, HttpResponse, HttpResponseForbidden, HttpRespon
 from django.middleware.gzip import GZipMiddleware
 from django.utils.decorators import decorator_from_middleware
 from django.utils.formats import localize
 from django.middleware.gzip import GZipMiddleware
 from django.utils.decorators import decorator_from_middleware
 from django.utils.formats import localize
+from django.utils.timezone import localtime
 from django.utils.translation import gettext as _
 from django.views.decorators.http import require_POST, require_GET
 from django.shortcuts import get_object_or_404, render
 from django.utils.translation import gettext as _
 from django.views.decorators.http import require_POST, require_GET
 from django.shortcuts import get_object_or_404, render
@@ -110,7 +111,7 @@ def editor_readonly(request, slug, chunk=None, template_name='wiki/document_deta
 
     access_time = datetime.now()
     last_books = request.session.get("wiki_last_books", {})
 
     access_time = datetime.now()
     last_books = request.session.get("wiki_last_books", {})
-    last_books[slug, chunk.slug] = {
+    last_books[reverse(editor, args=[chunk.book.slug, chunk.slug])] = {
         'time': mktime(access_time.timetuple()),
         'title': chunk.book.title,
         }
         'time': mktime(access_time.timetuple()),
         'title': chunk.book.title,
         }
@@ -369,11 +370,11 @@ def history(request, chunk_id):
                 "version": change.revision,
                 "description": change.description,
                 "author": change.author_str(),
                 "version": change.revision,
                 "description": change.description,
                 "author": change.author_str(),
-                "date": localize(change.created_at),
+                "date": localize(localtime(change.created_at)),
                 "publishable": change.publishable,
                 "tag": ',\n'.join(str(tag) for tag in change.tags.all()),
                 "published": _("Published") + ": " + \
                 "publishable": change.publishable,
                 "tag": ',\n'.join(str(tag) for tag in change.tags.all()),
                 "published": _("Published") + ": " + \
-                    localize(change.publish_log.order_by('-book_record__timestamp')[0].book_record.timestamp) \
+                    localize(localtime(change.publish_log.order_by('-book_record__timestamp')[0].book_record.timestamp)) \
                     if change.publish_log.exists() else "",
             })
     return JSONResponse(changes)
                     if change.publish_log.exists() else "",
             })
     return JSONResponse(changes)