Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

🔄 synced file(s) with WordPress/openverse (#1078)

Openverse (Bot)0f90f84d4bf8
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 89540ab63..434752d27 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -2,7 +2,7 @@
# here will be overwritten. Please make any necessary edits to these files:
# - https://github.com/WordPress/openverse/blob/main/.pre-commit-config.yaml.jinja
-exclude: Pipfile\.lock|migrations|\.idea|node_modules|archive
+exclude: Pipfile\.lock|migrations|\.idea|node_modules|archive|retired
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
@@ -30,7 +30,7 @@ repos:
# Use the `.isort.cfg` file to configure additional project-specific requirements.
- repo: https://github.com/PyCQA/isort
- rev: 5.9.1
+ rev: 5.12.0
hooks:
- id: isort
files: \.py$
@@ -62,6 +62,20 @@ repos:
args:
- --safe
+ - repo: https://github.com/pycqa/pydocstyle
+ rev: 6.2.2 # 6.2.3 is slightly broken
+ hooks:
+ - id: pydocstyle
+ args:
+ - --convention=pep257
+ # Additional ignore reasons:
+ # D1xx: we do not want to force contributors to write redundant or useless docstrings
+ # D202: additional whitespace helps with readability
+ # D211: same as D202
+ # See the following documentation for what each rule does:
+ # https://www.pydocstyle.org/en/6.2.3/error_codes.html#error-codes
+ - --add-ignore=D1,D202,D211
+
# Use the `.prettierignore` and `.prettier.config.js` files to configure project-specific requirements.
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.6.0
diff --git a/api/catalog/api/admin/site.py b/api/catalog/api/admin/site.py
index e1a66cdf5..8deebf90b 100644
--- a/api/catalog/api/admin/site.py
+++ b/api/catalog/api/admin/site.py
@@ -8,9 +8,10 @@ class OpenverseAdmin(admin.AdminSite):
def get_app_list(self, *args, **kwargs):
"""
- Modify the app and model list to present media specific models outside the main
- API group. This makes the long list easier to comprehend and locating the model
- of interest faster.
+ Present media specific models outside the main API group.
+
+ This modifies the app and model list to make it shorter and easier to
+ comprehend, thereby making it faster to locate the model of interest.
"""
app_list = super().get_app_list(*args, **kwargs)
diff --git a/api/catalog/api/constants/field_order.py b/api/catalog/api/constants/field_order.py
index 5b37e634c..bdcdb5ba4 100644
--- a/api/catalog/api/constants/field_order.py
+++ b/api/catalog/api/constants/field_order.py
@@ -1,6 +1,7 @@
"""
-This file hardcodes the logical order for serializer fields to be defined in so that
-their output feels suitable for human consumption.
+This file hardcodes the logical order for serializer fields.
+
+This leads to the JSON output being more suitable for human consumption.
"""
json_fields = [
diff --git a/api/catalog/api/constants/media_types.py b/api/catalog/api/constants/media_types.py
index 339a217c2..f31b66d86 100644
--- a/api/catalog/api/constants/media_types.py
+++ b/api/catalog/api/constants/media_types.py
@@ -1,6 +1,4 @@
-"""
-Also see `ingestion_server/constants/media_types.py`
-"""
+"""Also see `ingestion_server/constants/media_types.py`."""
AUDIO_TYPE = "audio"
IMAGE_TYPE = "image"
diff --git a/api/catalog/api/controllers/search_controller.py b/api/catalog/api/controllers/search_controller.py
index 79af78a91..ee1291702 100644
--- a/api/catalog/api/controllers/search_controller.py
+++ b/api/catalog/api/controllers/search_controller.py
@@ -39,8 +39,10 @@ class RankFeature(Query):
def _unmasked_query_end(page_size, page):
"""
- Used to retrieve the upper index of results to retrieve
- from Elasticsearch under the following conditions:
+ Calculate the upper index of results to retrieve from Elasticsearch.
+
+ Used to retrieve the upper index of results to retrieve from Elasticsearch under the
+ following conditions:
1. There is no query mask
2. The lower index is beyond the scope of the existing query mask
3. The lower index is within the scope of the existing query mask
@@ -55,8 +57,7 @@ def _paginate_with_dead_link_mask(
s: Search, page_size: int, page: int
) -> tuple[int, int]:
"""
- Given a query, a page and page_size, return the start and end
- of the slice of results.
+ Return the start and end of the results slice, given the query, page and page size.
In almost all cases the ``DEAD_LINK_RATIO`` will effectively double
the page size (given the current configuration of 0.5).
@@ -120,9 +121,8 @@ def _paginate_with_dead_link_mask(
def _get_query_slice(
s: Search, page_size: int, page: int, filter_dead: bool | None = False
) -> tuple[int, int]:
- """
- Select the start and end of the search results for this query.
- """
+ """Select the start and end of the search results for this query."""
+
if filter_dead:
start_slice, end_slice = _paginate_with_dead_link_mask(s, page_size, page)
else:
@@ -135,10 +135,8 @@ def _get_query_slice(
def _quote_escape(query_string):
- """
- If there are any unmatched quotes in the query supplied by the user, ignore
- them.
- """
+ """Ignore any unmatched quotes in the query supplied by the user."""
+
num_quotes = query_string.count('"')
if num_quotes % 2 == 1:
return query_string.replace('"', '\\"')
@@ -150,6 +148,8 @@ def _post_process_results(
s, start, end, page_size, search_results, request, filter_dead
) -> list[Hit] | None:
"""
+ Perform some steps on results fetched from the backend.
+
After fetching the search results from the back end, iterate through the
results, perform image validation, and route certain thumbnails through our
proxy.
@@ -227,8 +227,9 @@ def _apply_filter(
behaviour: Literal["filter", "exclude"] = "filter",
):
"""
- Parse and apply a filter from the search parameters serializer. The
- parameter key is assumed to have the same name as the corresponding
+ Parse and apply a filter from the search parameters serializer.
+
+ The parameter key is assumed to have the same name as the corresponding
Elasticsearch property. Each parameter value is assumed to be a comma
separated list encoded as a string.
@@ -254,9 +255,8 @@ def _apply_filter(
def _exclude_filtered(s: Search):
- """
- Hide data sources from the catalog dynamically.
- """
+ """Hide data sources from the catalog dynamically."""
+
filter_cache_key = "filtered_providers"
filtered_providers = cache.get(key=filter_cache_key)
if not filtered_providers:
@@ -288,8 +288,7 @@ def search(
page: int = 1,
) -> tuple[list[Hit], int, int]:
"""
- Given a set of keywords and an optional set of filters, perform a ranked
- paginated search.
+ Perform a ranked paginated search from the set of keywords and, optionally, filters.
:param search_params: Search parameters. See
:class: `ImageSearchQueryStringSerializer`.
@@ -423,9 +422,8 @@ def search(
def related_media(uuid, index, request, filter_dead):
- """
- Given a UUID, find related search results.
- """
+ """Given a UUID, find related search results."""
+
search_client = Search(index=index)
# Convert UUID to sequential ID.
@@ -506,8 +504,7 @@ def _get_result_and_page_count(
response_obj: Response, results: list[Hit] | None, page_size: int, page: int
) -> tuple[int, int]:
"""
- Elasticsearch does not allow deep pagination of ranked queries.
- Adjust returned page count to reflect this.
+ Adjust related page count because ES disallows deep pagination of ranked queries.
:param response_obj: The original Elasticsearch response object.
:param results: The list of filtered result Hits.
diff --git a/api/catalog/api/docs/media_docs.py b/api/catalog/api/docs/media_docs.py
index 00f74d637..e39895d8b 100644
--- a/api/catalog/api/docs/media_docs.py
+++ b/api/catalog/api/docs/media_docs.py
@@ -6,8 +6,7 @@ endpoint.
def fields_to_md(field_names):
"""
- Create a Markdown representation of the given list of names to use in
- Swagger documentation.
+ Create a Markdown representation of the given list of names to use in Swagger docs.
:param field_names: the list of field names to convert to Markdown
:return: the names as a Markdown string
diff --git a/api/catalog/api/models/audio.py b/api/catalog/api/models/audio.py
index a7bf88be4..a49d59ac0 100644
--- a/api/catalog/api/models/audio.py
+++ b/api/catalog/api/models/audio.py
@@ -43,9 +43,10 @@ class AltAudioFile(AbstractAltFile):
class AudioSet(ForeignIdentifierMixin, MediaMixin, FileMixin, OpenLedgerModel):
"""
- This is an ordered collection of audio files, such as a podcast series or
- an album. Not to be confused with AudioList which is a many-to-many
- collection of audio files, like a playlist or favourites library.
+ This is an ordered collection of audio files, such as a podcast series or an album.
+
+ Not to be confused with AudioList which is a many-to-many collection of audio files,
+ like a playlist or favourites library.
The FileMixin inherited by this model refers not to audio but album art.
"""
@@ -74,6 +75,7 @@ class AudioSet(ForeignIdentifierMixin, MediaMixin, FileMixin, OpenLedgerModel):
class AudioFileMixin(FileMixin):
"""
This mixin adds fields related to audio quality to the standard file mixin.
+
Do not use this as the sole base class.
"""
@@ -136,6 +138,8 @@ class AudioAddOn(OpenLedgerModel):
class Audio(AudioFileMixin, AbstractMedia):
"""
+ Represents one audio media instance.
+
Inherited fields
================
category: eg. music, sound_effect, podcast, news & audiobook
@@ -205,6 +209,7 @@ class Audio(AudioFileMixin, AbstractMedia):
def get_waveform(self) -> list[float]:
"""
Get the waveform if it exists. Return a blank list otherwise.
+
:return: the waveform, if it exists; empty list otherwise
"""
@@ -231,8 +236,10 @@ class Audio(AudioFileMixin, AbstractMedia):
class DeletedAudio(AbstractDeletedMedia):
"""
- Stores identifiers of audio tracks that have been deleted from the source. Do not
- create instances of this model manually. Create an ``AudioReport`` instance instead.
+ Stores identifiers of audio tracks that have been deleted from the source.
+
+ Do not create instances of this model manually. Create an ``AudioReport`` instance
+ instead.
"""
media_class = Audio
@@ -255,8 +262,10 @@ class DeletedAudio(AbstractDeletedMedia):
class MatureAudio(AbstractMatureMedia):
"""
- Stores all audio tracks that have been flagged as 'mature'. Do not create instances
- of this model manually. Create an ``AudioReport`` instance instead.
+ Stores all audio tracks that have been flagged as 'mature'.
+
+ Do not create instances of this model manually. Create an ``AudioReport`` instance
+ instead.
"""
media_class = Audio
diff --git a/api/catalog/api/models/image.py b/api/catalog/api/models/image.py
index 71afde538..8e2065ae8 100644
--- a/api/catalog/api/models/image.py
+++ b/api/catalog/api/models/image.py
@@ -16,8 +16,9 @@ from catalog.api.models.mixins import FileMixin
class ImageFileMixin(FileMixin):
"""
- This mixin adds fields related to image resolution to the standard file
- mixin. Do not use this as the sole base class.
+ This mixin adds fields related to image resolution to the standard file mixin.
+
+ Do not use this as the sole base class.
"""
width = models.IntegerField(
@@ -41,6 +42,8 @@ class ImageFileMixin(FileMixin):
class Image(ImageFileMixin, AbstractMedia):
"""
+ Represents one image media instance.
+
Inherited fields
================
category: eg. photograph, digitized_artwork & illustration
@@ -56,8 +59,10 @@ class Image(ImageFileMixin, AbstractMedia):
class DeletedImage(AbstractDeletedMedia):
"""
- Stores identifiers of images that have been deleted from the source. Do not create
- instances of this model manually. Create an ``ImageReport`` instance instead.
+ Stores identifiers of images that have been deleted from the source.
+
+ Do not create instances of this model manually. Create an ``ImageReport`` instance
+ instead.
"""
media_class = Image
@@ -77,8 +82,10 @@ class DeletedImage(AbstractDeletedMedia):
class MatureImage(AbstractMatureMedia):
"""
- Stores all images that have been flagged as 'mature'. Do not create instances of
- this model manually. Create an ``ImageReport`` instance instead.
+ Stores all images that have been flagged as 'mature'.
+
+ Do not create instances of this model manually. Create an ``ImageReport`` instance
+ instead.
"""
media_class = Image
diff --git a/api/catalog/api/models/media.py b/api/catalog/api/models/media.py
index a44b16db0..c38ac9ce9 100644
--- a/api/catalog/api/models/media.py
+++ b/api/catalog/api/models/media.py
@@ -30,8 +30,9 @@ class AbstractMedia(
IdentifierMixin, ForeignIdentifierMixin, MediaMixin, OpenLedgerModel
):
"""
- Generic model from which to inherit all media classes. This class stores
- information common to all media types indexed by Openverse.
+ Generic model from which to inherit all media classes.
+
+ This class stores information common to all media types indexed by Openverse.
"""
watermarked = models.BooleanField(blank=True, null=True)
@@ -99,8 +100,10 @@ class AbstractMedia(
@property
def attribution(self) -> str:
"""
- The plain-text English attribution for a media item. Use this to credit creators
- for their work and fulfill legal attribution requirements.
+ The plain-text English attribution for a media item.
+
+ Use this to credit creators for their work and fulfill legal attribution
+ requirements.
"""
return get_attribution_text(
@@ -113,8 +116,9 @@ class AbstractMedia(
class Meta:
"""
- Meta class for all media types indexed by Openverse. All concrete media
- classes should inherit their Meta class from this.
+ Meta class for all media types indexed by Openverse.
+
+ All concrete media classes should inherit their Meta class from this.
"""
ordering = ["-created_on"]
@@ -129,6 +133,7 @@ class AbstractMedia(
def __str__(self):
"""
Return the string representation of the model, used in the Django admin site.
+
:return: the string representation of the model
"""
@@ -137,8 +142,9 @@ class AbstractMedia(
class AbstractMediaReport(models.Model):
"""
- Generic model from which to inherit all reported media classes. 'Reported'
- here refers to content reports such as mature, copyright-violating or
+ Generic model from which to inherit all reported media classes.
+
+ 'Reported' here refers to content reports such as mature, copyright-violating or
deleted content. Subclasses must populate ``media_class``, ``mature_class`` and
``deleted_class`` fields.
"""
@@ -195,9 +201,7 @@ class AbstractMediaReport(models.Model):
abstract = True
def clean(self):
- """
- This function raises errors that can be handled by Django's admin interface.
- """
+ """Clean fields and raise errors that can be handled by Django Admin."""
if not self.media_class.objects.filter(
identifier=self.media_obj.identifier
@@ -215,8 +219,10 @@ class AbstractMediaReport(models.Model):
def save(self, *args, **kwargs):
"""
- Extend the ``save()`` functionality with Elasticsearch integration to
- update records and refresh indices.
+ Save changes to the DB and sync them with Elasticsearch.
+
+ Extend the built-in ``save()`` functionality of Django with Elasticsearch
+ integration to update records and refresh indices.
Media marked as mature or deleted also leads to instantiation of their
corresponding mature or deleted classes.
@@ -247,8 +253,9 @@ class AbstractMediaReport(models.Model):
class AbstractDeletedMedia(OpenLedgerModel):
"""
- Generic model from which to inherit all deleted media classes. 'Deleted'
- here refers to media which has been deleted at the source or intentionally
+ Generic model from which to inherit all deleted media classes.
+
+ 'Deleted' here refers to media which has been deleted at the source or intentionally
de-indexed by us. Unlike mature reports, this action is irreversible. Subclasses
must populate ``media_class`` and ``es_index`` fields.
"""
@@ -298,8 +305,9 @@ class AbstractDeletedMedia(OpenLedgerModel):
class AbstractMatureMedia(models.Model):
"""
- Generic model from which to inherit all mature media classes. Subclasses must
- populate ``media_class`` and ``es_index`` fields.
+ Generic model from which to inherit all mature media classes.
+
+ Subclasses must populate ``media_class`` and ``es_index`` fields.
"""
media_class: type[models.Model] = None
@@ -361,8 +369,10 @@ class AbstractMatureMedia(models.Model):
class AbstractMediaList(OpenLedgerModel):
"""
- Generic model from which to inherit media lists. Each subclass should define
- its own `ManyToManyField` to point to a subclass of `AbstractMedia`.
+ Generic model from which to inherit media lists.
+
+ Each subclass should define its own `ManyToManyField` to point to a subclass of
+ `AbstractMedia`.
"""
title = models.CharField(max_length=2000, help_text="Display name")
@@ -412,6 +422,7 @@ class AbstractAltFile:
def mime_type(self):
"""
Get the MIME type of the file inferred from the extension of the file.
+
:return: the inferred MIME type of the file
"""
diff --git a/api/catalog/api/models/mixins.py b/api/catalog/api/models/mixins.py
index 69782a075..406fe3ba4 100644
--- a/api/catalog/api/models/mixins.py
+++ b/api/catalog/api/models/mixins.py
@@ -5,8 +5,9 @@ from django.db import models
class IdentifierMixin(models.Model):
"""
- This mixin adds fields related to unique ID, both internal and external, to
- any model. Do not use this as the sole base class.
+ This mixin adds fields related to unique ID, both internal and external, to a model.
+
+ Do not use this as the sole base class.
The mixins adds
@@ -25,8 +26,9 @@ class IdentifierMixin(models.Model):
class ForeignIdentifierMixin(models.Model):
"""
- This mixin adds fields related to the external unique ID to any model. Do
- not use this as the sole base class.
+ This mixin adds fields related to the external unique ID to any model.
+
+ Do not use this as the sole base class.
This mixin adds
@@ -47,8 +49,9 @@ class ForeignIdentifierMixin(models.Model):
class MediaMixin(models.Model):
"""
- This mixin adds fields related to a creative creation such as the title of
- the work and info about the artist. Do not use this as the sole base class.
+ This mixin adds fields related to a creation such as the title and artist info.
+
+ Do not use this as the sole base class.
The mixin adds
@@ -111,8 +114,9 @@ class MediaMixin(models.Model):
class FileMixin(models.Model):
"""
- This mixin adds fields related to file such as the file URL and size to any
- model. Do not use this as the sole base class.
+ This mixin adds fields related to file such as the file URL and size to any model.
+
+ Do not use this as the sole base class.
This mixin adds
@@ -153,6 +157,7 @@ class FileMixin(models.Model):
def mime_type(self):
"""
Get the MIME type of the file inferred from the extension of the file.
+
:return: the inferred MIME type of the file
"""
diff --git a/api/catalog/api/models/models.py b/api/catalog/api/models/models.py
index b7911ac58..f06b9c6ec 100644
--- a/api/catalog/api/models/models.py
+++ b/api/catalog/api/models/models.py
@@ -6,8 +6,9 @@ from catalog.api.models.base import OpenLedgerModel
class ContentProvider(models.Model):
"""
- A content provider instance can only be mapped to a single media type. For
- providers providing multiple media types, use different identifiers while
+ A content provider instance can only be mapped to a single media type.
+
+ For providers providing multiple media types, use different identifiers while
keeping the same display name.
For example,
diff --git a/api/catalog/api/models/oauth.py b/api/catalog/api/models/oauth.py
index fbb7bb908..50e6fb920 100644
--- a/api/catalog/api/models/oauth.py
+++ b/api/catalog/api/models/oauth.py
@@ -4,9 +4,7 @@ from oauth2_provider.models import AbstractApplication
class OAuth2Registration(models.Model):
- """
- Information about API key applicants.
- """
+ """Information about API key applicants."""
name = models.CharField(
max_length=150,
@@ -27,9 +25,7 @@ class OAuth2Registration(models.Model):
class ThrottledApplication(AbstractApplication):
- """
- An OAuth2 application with adjustable rate limits.
- """
+ """An OAuth2 application with adjustable rate limits."""
RATE_LIMIT_MODELS = [
("standard", "standard"), # Default rate limit for all API keys.
@@ -46,8 +42,9 @@ class ThrottledApplication(AbstractApplication):
class OAuth2Verification(models.Model):
"""
- An email verification code sent by noreply-catalog. After verification
- occurs, the entry should be deleted.
+ An email verification code sent by noreply-catalog.
+
+ After verification occurs, the entry should be deleted.
"""
associated_application = models.ForeignKey(
diff --git a/api/catalog/api/serializers/audio_serializers.py b/api/catalog/api/serializers/audio_serializers.py
index ab644e3a7..40b8720e3 100644
--- a/api/catalog/api/serializers/audio_serializers.py
+++ b/api/catalog/api/serializers/audio_serializers.py
@@ -175,8 +175,9 @@ class AudioSerializer(AudioHyperlinksSerializer, MediaSerializer):
class AudioSearchSerializer(MediaSearchSerializer):
"""
The full audio search response.
- This serializer is purely representational and not actually used to
- serialize the response.
+
+ This serializer is purely representational and not actually used to serialize the
+ response.
"""
results = AudioSerializer(
diff --git a/api/catalog/api/serializers/base.py b/api/catalog/api/serializers/base.py
index 1affab8c5..185a35074 100644
--- a/api/catalog/api/serializers/base.py
+++ b/api/catalog/api/serializers/base.py
@@ -2,14 +2,13 @@ from rest_framework import serializers
class BaseModelSerializer(serializers.ModelSerializer):
- """
- Extends model serializer to use docstring of properties as help text.
- """
+ """Extends model serializer to use docstring of properties as help text."""
def build_property_field(self, field_name, model_class):
"""
- Overrides the built-in property field builder to use docstrings as the Swagger
- help text for fields.
+ Use docstrings as the Swagger help text for fields.
+
+ This is accomplished by overriding the built-in property field builder.
:param field_name: the name of the property for which the field is being built
:param model_class: the ``class`` instance for the Django model
diff --git a/api/catalog/api/serializers/error_serializers.py b/api/catalog/api/serializers/error_serializers.py
index 1a93f85cd..bc322f717 100644
--- a/api/catalog/api/serializers/error_serializers.py
+++ b/api/catalog/api/serializers/error_serializers.py
@@ -1,4 +1,6 @@
"""
+These serializers handle error responses sent by API endpoints.
+
Reference for exception handling in Django REST Framework:
https://www.django-rest-framework.org/api-guide/exceptions/
"""
diff --git a/api/catalog/api/serializers/fields.py b/api/catalog/api/serializers/fields.py
index f21e2c7ba..ab91f7ea1 100644
--- a/api/catalog/api/serializers/fields.py
+++ b/api/catalog/api/serializers/fields.py
@@ -30,9 +30,7 @@ class SchemableHyperlinkedIdentityField(serializers.HyperlinkedIdentityField):
class EnumCharField(serializers.CharField):
- """
- This field extends the ``CharField`` to add enum validation.
- """
+ """This field extends the ``CharField`` to add enum validation."""
default_error_messages = serializers.CharField.default_error_messages | {
"outside_enum": "Invalid value: {given}. Allowed values: {allowed}"
diff --git a/api/catalog/api/serializers/image_serializers.py b/api/catalog/api/serializers/image_serializers.py
index 92a0f1118..1e2dd32c0 100644
--- a/api/catalog/api/serializers/image_serializers.py
+++ b/api/catalog/api/serializers/image_serializers.py
@@ -108,6 +108,7 @@ class ImageSerializer(ImageHyperlinksSerializer, MediaSerializer):
class ImageSearchSerializer(MediaSearchSerializer):
"""
The full image search response.
+
This serializer is purely representational and not actually used to
serialize the response.
"""
@@ -140,8 +141,10 @@ class OembedRequestSerializer(serializers.Serializer):
class OembedSerializer(BaseModelSerializer):
"""
- The embedded content from a specified image URL. This is essentially an
- ``ImageSerializer`` with some changes to match the oEmbed spec: https://oembed.com.
+ The embedded content from a specified image URL.
+
+ This is essentially an ``ImageSerializer`` with some changes to match the oEmbed
+ spec: https://oembed.com.
"""
version = serializers.ReadOnlyField(
diff --git a/api/catalog/api/serializers/media_serializers.py b/api/catalog/api/serializers/media_serializers.py
index 0229d3537..2379be4aa 100644
--- a/api/catalog/api/serializers/media_serializers.py
+++ b/api/catalog/api/serializers/media_serializers.py
@@ -22,9 +22,7 @@ from catalog.api.utils.url import add_protocol
class MediaSearchRequestSerializer(serializers.Serializer):
- """
- This serializer parses and validates search query string parameters.
- """
+ """This serializer parses and validates search query string parameters."""
DeprecatedParam = namedtuple("DeprecatedParam", ["original", "successor"])
deprecated_params = [
@@ -137,7 +135,7 @@ class MediaSearchRequestSerializer(serializers.Serializer):
@staticmethod
def validate_license(value):
- """Checks whether license is a valid license code."""
+ """Check whether license is a valid license code."""
licenses = value.lower().split(",")
for _license in licenses:
@@ -150,7 +148,7 @@ class MediaSearchRequestSerializer(serializers.Serializer):
@staticmethod
def validate_license_type(value):
- """Checks whether license type is a known collection of licenses."""
+ """Check whether license type is a known collection of licenses."""
license_types = value.lower().split(",")
license_groups = []
@@ -224,9 +222,7 @@ class MediaSearchRequestSerializer(serializers.Serializer):
class MediaThumbnailRequestSerializer(serializers.Serializer):
- """
- This serializer parses and validates thumbnail query string parameters.
- """
+ """This serializer parses and validates thumbnail query string parameters."""
full_size = serializers.BooleanField(
source="is_full_size",
@@ -273,9 +269,7 @@ class MediaReportRequestSerializer(serializers.ModelSerializer):
class TagSerializer(serializers.Serializer):
- """
- This output serializer serializes a singular tag.
- """
+ """This output serializer serializes a singular tag."""
name = serializers.CharField(
help_text="The name of a detailed tag.",
@@ -289,8 +283,9 @@ class TagSerializer(serializers.Serializer):
class MediaSearchSerializer(serializers.Serializer):
"""
- This serializer serializes the full media search response. The class should
- be inherited by all individual media serializers.
+ This serializer serializes the full media search response.
+
+ The class should be inherited by all individual media serializers.
"""
result_count = serializers.IntegerField(
@@ -310,8 +305,9 @@ class MediaSearchSerializer(serializers.Serializer):
class MediaSerializer(BaseModelSerializer):
"""
- This serializer serializes a single media file. The class should be
- inherited by all individual media serializers.
+ This serializer serializes a single media file.
+
+ The class should be inherited by all individual media serializers.
"""
class Meta:
@@ -397,10 +393,7 @@ class MediaSerializer(BaseModelSerializer):
def get_search_request_source_serializer(media_type):
class MediaSearchRequestSourceSerializer(serializers.Serializer):
- """
- This serializer parses and validates the source/not_source fields from the query
- parameters.
- """
+ """Parses and validates the source/not_source fields from the query params."""
field_names = [
"source",
@@ -429,7 +422,7 @@ def get_search_request_source_serializer(media_type):
@staticmethod
def validate_source_field(value):
- """Checks whether source is a valid source."""
+ """Check whether source is a valid source."""
allowed_sources = list(search_controller.get_sources(media_type).keys())
sources = value.lower().split(",")
@@ -458,8 +451,9 @@ def get_search_request_source_serializer(media_type):
def get_hyperlinks_serializer(media_type):
class MediaHyperlinksSerializer(serializers.Serializer):
"""
- This serializer creates URLs pointing to other endpoints related with this media
- item such as details and related media.
+ This serializer creates URLs pointing to other endpoints for this media item.
+
+ These URLs include the thumbnail, details page and list of related media.
"""
field_names = [
diff --git a/api/catalog/api/utils/attribution.py b/api/catalog/api/utils/attribution.py
index d8dd4b1c3..7987e2dac 100644
--- a/api/catalog/api/utils/attribution.py
+++ b/api/catalog/api/utils/attribution.py
@@ -1,5 +1,6 @@
"""
This module highly mirrors the JavaScript code present in the frontend repository.
+
For any changes made here, please make the corresponding changes in the
frontend, or open an issue to track it.
"""
@@ -15,8 +16,9 @@ def get_attribution_text(
license_url: str | None,
) -> str:
"""
- Get the attribution text to properly and legally attribute a creative work to its
- creator. This text is only in plain-text English. Refer to the frontend for an
+ Get the text to properly and legally attribute a creative work to its creator.
+
+ This text is only in plain-text English. Refer to the frontend for an
internationalised implementation with rich-text and HTML variants.
:param title: the title of the creative work
diff --git a/api/catalog/api/utils/ccrel.py b/api/catalog/api/utils/ccrel.py
index 58cc59bb7..e12dc5880 100644
--- a/api/catalog/api/utils/ccrel.py
+++ b/api/catalog/api/utils/ccrel.py
@@ -1,12 +1,13 @@
"""
-Tools for embedding Creative Commons Rights Expression Language (ccREL) data
-into files using Extensible Metadata Platform (XMP).
+Tools for embedding ccREL data into files using XMP.
+
+ccREL stands for Creative Commons Rights Expression Language. XMP stands for Extensible
+Metadata Platform.
This implementation is specifically for embedding ccREL inside of images, but it
could be extended to handle other types of content.
-For more information, see the ccREL W3 standard [0].
-[0] https://www.w3.org/Submission/ccREL/
+For more information, see the [ccREL W3 standard](https://www.w3.org/Submission/ccREL/).
"""
import io
@@ -19,7 +20,8 @@ from libxmp.consts import XMP_NS_CC, XMP_NS_XMP, XMP_NS_XMP_Rights
def embed_xmp_bytes(image: io.BytesIO, work_properties):
"""
- Given a file-like `io.BytesIO` object, embed ccREL metadata inside of it.
+ Embed ccREL metadata inside a file-like `io.BytesIO` object.
+
For our purposes, we assume that the file is an image.
:param image: A BytesIO representation of an image.
diff --git a/api/catalog/api/utils/dead_link_mask.py b/api/catalog/api/utils/dead_link_mask.py
index 8980439fa..4d0cc281d 100644
--- a/api/catalog/api/utils/dead_link_mask.py
+++ b/api/catalog/api/utils/dead_link_mask.py
@@ -9,6 +9,8 @@ DEAD_LINK_MASK_TTL = 60 * 60 * 3
def get_query_hash(s: Search) -> str:
"""
+ Hash the search query using a deterministic algorithm.
+
Generates a deterministic Murmur3 or SHA256 hash from the serialized Search
object using DeepHash so that two Search objects with the same content will
produce the same hash.
@@ -25,8 +27,7 @@ def get_query_hash(s: Search) -> str:
def get_query_mask(query_hash: str) -> list[int]:
"""
- Fetches an existing query mask for a given query hash
- or returns an empty one.
+ Fetch an existing query mask for a given query hash or returns an empty one.
:param query_hash: Unique value for a particular query.
:return: Boolean mask as a list of integers (0 or 1).
@@ -38,7 +39,7 @@ def get_query_mask(query_hash: str) -> list[int]:
def save_query_mask(query_hash: str, mask: list):
"""
- Saves a query mask to redis.
+ Save a query mask to redis.
:param mask: Boolean mask as a list of integers (0 or 1).
:param query_hash: Unique value to be used as key.
diff --git a/api/catalog/api/utils/exceptions.py b/api/catalog/api/utils/exceptions.py
index 4fd7e7058..1db366e73 100644
--- a/api/catalog/api/utils/exceptions.py
+++ b/api/catalog/api/utils/exceptions.py
@@ -4,7 +4,9 @@ from rest_framework.views import exception_handler as drf_exception_handler
def exception_handler(ex, context):
"""
- Handle the exception raised in a DRF context. See `DRF docs`_.
+ Handle the exception raised in a DRF context.
+
+ See `DRF docs`_.
.. _DRF docs: https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling # noqa: E501
:param ex: the exception that has occurred
diff --git a/api/catalog/api/utils/help_text.py b/api/catalog/api/utils/help_text.py
index d041e765f..f3d80c6c9 100644
--- a/api/catalog/api/utils/help_text.py
+++ b/api/catalog/api/utils/help_text.py
@@ -3,14 +3,16 @@ from collections.abc import Iterable
def make_comma_separated_help_text(items: Iterable[str], name: str) -> str:
"""
- Generate help text that describes a comma separated list of items with the name
- provided. Items are wrapped in backticks, and lists with more than one item will
+ Generate help text containing a comma separated list of items with the given name.
+
+ Items are wrapped in backticks, and lists with more than one item will
have an "and" added before the final item.
:param items: iterable of available options for this field
:param name: plural name of the list of items (e.g. "categories", "aspect ratios")
:return: generated help text
"""
+
formatted = [f"`{item}`" for item in sorted(items)]
# Add an "and" at the end of the list
if len(formatted) > 1:
diff --git a/api/catalog/api/utils/licenses.py b/api/catalog/api/utils/licenses.py
index 6d658322e..417acba70 100644
--- a/api/catalog/api/utils/licenses.py
+++ b/api/catalog/api/utils/licenses.py
@@ -1,5 +1,6 @@
"""
This module highly mirrors the JavaScript code present in the frontend repository.
+
For any changes made here, please make the corresponding changes in the
frontend, or open an issue to track it.
"""
@@ -34,8 +35,7 @@ def get_license_url(_license: str, license_version: str | None) -> str:
def get_full_license_name(_license: str, license_version: str | None) -> str:
"""
- Get the full name of the license in a displayable format from the license
- slug and version.
+ Get the readable full name of the license from the license slug and version.
:param _license: the slug of the license
:param license_version: the version number of the license
@@ -56,9 +56,10 @@ def get_full_license_name(_license: str, license_version: str | None) -> str:
def is_public_domain(_license: str) -> bool:
"""
+ Check if the given name belongs to a public-domain mark and is not a license.
+
CC licenses have different legal status from the public domain marks
- such as CC0 and PDM, and need different wording. Check if the given name
- belongs to a public-domain mark and is not a license.
+ such as CC0 and PDM, and need different wording.
:param _license: the license slug to check
:return: ``True`` if the license is a public domain mark, ``False`` otherwise
@@ -69,8 +70,9 @@ def is_public_domain(_license: str) -> bool:
def is_cc(_license: str) -> bool:
"""
- Check if the given name belongs to a CC license, active or deprecated. This
- includes CC0, which although not technically a license, is offered by CC.
+ Check if the given name belongs to a CC license, active or deprecated.
+
+ This includes CC0, which although not technically a license, is offered by CC.
:param _license: the license slug to check
:return: ``True`` if the license is a CC license, ``False`` otherwise
@@ -81,8 +83,9 @@ def is_cc(_license: str) -> bool:
def is_deprecated(_license: str) -> bool:
"""
- Check if the given name belongs to a deprecated CC license. The full list of
- deprecated licenses can be found on the
+ Check if the given name belongs to a deprecated CC license.
+
+ The full list of deprecated licenses can be found on the
[Retired Legal Tools page](https://creativecommons.org/retiredlicenses/) on
the CC.org site.
diff --git a/api/catalog/api/utils/oauth2_helper.py b/api/catalog/api/utils/oauth2_helper.py
index 02a6c99de..b2c37857f 100644
--- a/api/catalog/api/utils/oauth2_helper.py
+++ b/api/catalog/api/utils/oauth2_helper.py
@@ -13,8 +13,7 @@ _no_result = (None, None, None)
def get_token_info(token: str):
"""
- Recover an OAuth2 application client ID and rate limit model from an access
- token.
+ Recover an OAuth2 application client ID and rate limit model from an access token.
:param token: An OAuth2 access token.
:return: If the token is valid, return the client ID associated with the
diff --git a/api/catalog/api/utils/scheduled_tasks.py b/api/catalog/api/utils/scheduled_tasks.py
index c11563dfa..66d01f416 100644
--- a/api/catalog/api/utils/scheduled_tasks.py
+++ b/api/catalog/api/utils/scheduled_tasks.py
@@ -1,7 +1,8 @@
"""
-Cron-like tasks run at a set interval. `python3 manage.py runcrons` will
-execute any scheduled tasks. This is intended to run on all instances of the
-server.
+Cron-like tasks run at a set interval.
+
+`python3 manage.py runcrons` will execute any scheduled tasks. This is intended to run
+on all instances of the server.
Even though there may be multiple instances of the server running, a job is
guaranteed to execute only once. Jobs are not run unless it can acquire a lock
@@ -24,6 +25,8 @@ model_name_to_instance = {"Image": Image}
class SaveCachedTrafficStats(CronJobBase):
"""
+ Handle recording of stats to cache and periodically persisting them in the DB.
+
Traffic statistics (view count, API usage) are stored in Redis for fast
updates and retrieval. In order to ensure durability of statistics and
minimize cache memory requirements, they are intermittently replicated to
diff --git a/api/catalog/api/utils/status_code_view.py b/api/catalog/api/utils/status_code_view.py
index bef409475..d9118fdc9 100644
--- a/api/catalog/api/utils/status_code_view.py
+++ b/api/catalog/api/utils/status_code_view.py
@@ -6,8 +6,9 @@ from django.views.generic import View
def get_status_code_view(data, status_code=200):
"""
- Get a class-based view that returns the given data and status code on all
- HTTP methods. Useful for blanket discontinuation of API endpoints.
+ Get a class-based view that returns the same response on all HTTP methods.
+
+ This is useful for blanket discontinuation of API endpoints.
:param data: the dictionary to serialize as the JSON response
:param status_code: the status code of the returned response
diff --git a/api/catalog/api/utils/throttle.py b/api/catalog/api/utils/throttle.py
index 3329bbfe1..5ff5bd6dd 100644
--- a/api/catalog/api/utils/throttle.py
+++ b/api/catalog/api/utils/throttle.py
@@ -71,9 +71,9 @@ class OnePerSecond(AbstractAnonRateThrottle):
class AbstractOAuth2IdRateThrottle(SimpleRateThrottle, metaclass=abc.ABCMeta):
"""
- Ties a particular configured throttling scope from ``settings.py`` to
- a "rate limit model". See ``ThrottledApplication.rate_limit_model``
- for an explanation of that concept.
+ Ties a particular throttling scope from ``settings.py`` to a rate limit model.
+
+ See ``ThrottledApplication.rate_limit_model`` for an explanation of that concept.
"""
scope: str
diff --git a/api/catalog/api/utils/url.py b/api/catalog/api/utils/url.py
index 6e5ad28a8..49ea3c030 100644
--- a/api/catalog/api/utils/url.py
+++ b/api/catalog/api/utils/url.py
@@ -3,9 +3,11 @@ from urllib.parse import urlparse
def add_protocol(url: str) -> str:
"""
+ Add protocol to URLs that lack them.
+
Some fields in the database contain incomplete URLs, leading to unexpected
- behavior in downstream consumers. This helper verifies that we always return
- fully formed URLs in such situations.
+ behavior in downstream consumers. This helper verifies that we always
+ return fully formed URLs in such situations.
:param url: the URL to check and add scheme
:return: the URL with the existing scheme, or ``https`` if one did not exist
diff --git a/api/catalog/api/utils/validate_images.py b/api/catalog/api/utils/validate_images.py
index 21560a673..1bfcab7ac 100644
--- a/api/catalog/api/utils/validate_images.py
+++ b/api/catalog/api/utils/validate_images.py
@@ -56,9 +56,10 @@ def validate_images(
query_hash: str, start_slice: int, results: list[Hit], image_urls: list[str]
) -> None:
"""
- Make sure images exist before we display them. Treat redirects as broken
- links since 99% of the time the redirect leads to a generic "not found"
- placeholder.
+ Make sure images exist before we display them.
+
+ Treat redirects as broken links since most of the time the redirect leads to a
+ generic "not found" placeholder.
Results are cached in redis and shared amongst all API servers in the
cluster.
diff --git a/api/catalog/api/utils/watermark.py b/api/catalog/api/utils/watermark.py
index d8a70e5f4..786e5e6b8 100644
--- a/api/catalog/api/utils/watermark.py
+++ b/api/catalog/api/utils/watermark.py
@@ -28,9 +28,7 @@ HEADERS = {
class Dimension(Flag):
- """
- This enum represents the two dimensions of an image
- """
+ """This enum represents the two dimensions of an image."""
HEIGHT = auto()
WIDTH = auto()
@@ -43,7 +41,8 @@ class Dimension(Flag):
def _smaller_dimension(width, height):
"""
- Determine which image dimensions are below the breakpoint dimensions
+ Determine which image dimensions are below the breakpoint dimensions.
+
:param width: the width of the image
:param height: the height of the image
:return: True if the image is small, False otherwise
@@ -59,7 +58,8 @@ def _smaller_dimension(width, height):
def _get_font_path(monospace=False):
"""
- Return the path to the TTF font file
+ Return the path to the TTF font file.
+
:param monospace: True for monospaced font, False for variable-width font
:return: the path to the TTF font file
"""
@@ -72,7 +72,8 @@ def _get_font_path(monospace=False):
def _fit_in_width(text, font, max_width):
"""
- Break the given text so that it fits in the given space
+ Break the given text so that it fits in the given space.
+
:param text: the text to fit in the limited width
:param font: the font containing size and other info
:param max_width: the maximum width the text is allowed to take
@@ -92,7 +93,8 @@ def _fit_in_width(text, font, max_width):
def _create_frame(dimensions):
"""
- Creates an frame with the given dimensions
+ Create a frame with the given dimensions.
+
:param dimensions: a tuple containing the width and height of the frame
:return: a white frame with the given dimensions
"""
@@ -102,7 +104,8 @@ def _create_frame(dimensions):
def _frame_image(image, frame, left_margin, top_margin):
"""
- Fix the image in the frame with the specified spacing
+ Fix the image in the frame with the specified spacing.
+
:param image: the image to frame
:param frame: the frame in which to fit the image
:param left_margin: the margin to the left of the image
@@ -119,7 +122,8 @@ def _frame_image(image, frame, left_margin, top_margin):
def _full_license(image_info):
"""
- Get the full license from the image info
+ Get the full license from the image info.
+
:param image_info: the information about a particular image
:return: the full license text for the image
"""
@@ -133,7 +137,8 @@ def _full_license(image_info):
def _get_attribution_text(image_info):
"""
- Generate the attribution text from the image info
+ Generate the attribution text from the image info.
+
:param image_info: the info pertaining to the licensing of the image
:return: the attribution text
"""
@@ -150,7 +155,8 @@ def _get_attribution_text(image_info):
def _open_image(url):
"""
- Read an image from a URL and convert it into a PIL Image object
+ Read an image from a URL and convert it into a PIL Image object.
+
:param url: the URL from where to read the image
:return: the PIL image object with the EXIF data
"""
@@ -174,7 +180,8 @@ def _open_image(url):
def _print_attribution_on_image(img, image_info):
"""
- Add a frame around the image and put the attribution text on the bottom
+ Add a frame around the image and put the attribution text on the bottom.
+
:param img: the image to frame and attribute
:param image_info: the information about a particular image
:return: return the framed and attributed image
@@ -230,7 +237,7 @@ def _print_attribution_on_image(img, image_info):
def watermark(image_url, info, draw_frame=True):
"""
- Returns a PIL Image with a watermark and embedded metadata.
+ Return a PIL Image with a watermark and embedded metadata.
:param image_url: The URL of the image.
:param info: A dictionary with keys title, creator, license, and
diff --git a/api/catalog/api/utils/waveform.py b/api/catalog/api/utils/waveform.py
index 77bac9954..22e13f7aa 100644
--- a/api/catalog/api/utils/waveform.py
+++ b/api/catalog/api/utils/waveform.py
@@ -20,12 +20,14 @@ UA_STRING = settings.OUTBOUND_USER_AGENT_TEMPLATE.format(purpose="Waveform")
def ext_from_url(url):
"""
- Get the file extension from the given URL. Looks at the last part of the URL
- path, and returns the string after the last dot.
+ Get the file extension from the given URL.
+
+ Looks at the last part of the URL path, and returns the string after the last dot.
:param url: the URL to the file whose extension is being determined
:returns: the file extension or ``None``
"""
+
file_name = url.split("/")[-1]
if "." in file_name:
ext = file_name.split(".")[-1]
@@ -42,6 +44,7 @@ def download_audio(url, identifier):
:param identifier: the identifier of the media object to name the file
:returns: the name of the file on the disk
"""
+
logger = parent_logger.getChild("download_audio")
logger.info(f"downloading file url={url}")
@@ -63,12 +66,14 @@ def download_audio(url, identifier):
def generate_waveform(file_name, duration):
"""
Generate the waveform for the file by invoking the ``audiowaveform`` binary.
+
The Python module ``subprocess`` is used to execute the binary and get the
results that it emits to STDOUT.
:param file_name: the name of the downloaded audio file
:param duration: the duration of the audio to determine pixels per second
"""
+
logger = parent_logger.getChild("generate_waveform")
logger.info("Invoking audiowaveform")
@@ -90,14 +95,16 @@ def generate_waveform(file_name, duration):
def process_waveform_output(json_out):
"""
- Parse the waveform output generated by the ``audiowaveform`` binary. The
- output consists of alternating positive and negative values, that are almost
+ Parse the waveform output generated by the ``audiowaveform`` binary.
+
+ The output consists of alternating positive and negative values, that are almost
equal in amplitude. We discard the negative values. We also scale down the
amplitudes by the largest value so that they lie in the range [0, 1].
:param json_out: the JSON output generated by ``audiowaveform``
:returns: the list of peaks
"""
+
logger = parent_logger.getChild("process_waveform_output")
logger.info("Transforming points")
@@ -128,6 +135,7 @@ def cleanup(file_name):
:param file_name: the name of the file to delete
"""
+
logger = parent_logger.getChild("cleanup")
file_path = TMP_DIR.joinpath(file_name)
diff --git a/api/catalog/api/views/audio_views.py b/api/catalog/api/views/audio_views.py
index 26e733cc9..fb65cd78a 100644
--- a/api/catalog/api/views/audio_views.py
+++ b/api/catalog/api/views/audio_views.py
@@ -35,9 +35,7 @@ from catalog.api.views.media_views import MediaViewSet
@method_decorator(swagger_auto_schema(**AudioThumbnail.swagger_setup), "thumbnail")
@method_decorator(swagger_auto_schema(auto_schema=None), "waveform")
class AudioViewSet(MediaViewSet):
- """
- Viewset for all endpoints pertaining to audio.
- """
+ """Viewset for all endpoints pertaining to audio."""
model_class = Audio
query_serializer_class = AudioSearchRequestSerializer
diff --git a/api/catalog/api/views/health_views.py b/api/catalog/api/views/health_views.py
index b744094a5..314199a52 100644
--- a/api/catalog/api/views/health_views.py
+++ b/api/catalog/api/views/health_views.py
@@ -12,8 +12,7 @@ class ElasticsearchHealthcheckException(APIException):
class HealthCheck(APIView):
"""
- Returns a "200 OK" response if the server is running normally. Returns 503
- otherwise.
+ Return a "200 OK" response if the server is running normally, 503 otherwise.
This endpoint is used in production to ensure that the server should receive
traffic. If no response is provided, the server is deregistered from the
@@ -23,9 +22,8 @@ class HealthCheck(APIView):
swagger_schema = None
def _check_es(self) -> Response | None:
- """
- Checks Elasticsearch cluster health. Raises an exception if ES is not healthy.
- """
+ """Check ES cluster health and raise an exception if ES is not healthy."""
+
es_health = settings.ES.cluster.health(timeout="5s")
if es_health["timed_out"]:
diff --git a/api/catalog/api/views/image_views.py b/api/catalog/api/views/image_views.py
index f4a61118d..05389b532 100644
--- a/api/catalog/api/views/image_views.py
+++ b/api/catalog/api/views/image_views.py
@@ -52,9 +52,7 @@ from catalog.api.views.media_views import MediaViewSet
@method_decorator(swagger_auto_schema(**ImageThumbnail.swagger_setup), "thumbnail")
@method_decorator(swagger_auto_schema(auto_schema=None), "watermark")
class ImageViewSet(MediaViewSet):
- """
- Viewset for all endpoints pertaining to images.
- """
+ """Viewset for all endpoints pertaining to images."""
model_class = Image
query_serializer_class = ImageSearchRequestSerializer
@@ -195,10 +193,8 @@ class ImageViewSet(MediaViewSet):
@staticmethod
def _save_wrapper(pil_img, exif_bytes, destination):
- """
- PIL crashes if exif_bytes=None, so we have to wrap it to avoid littering
- the code with branches.
- """
+ """Prevent PIL from crashing if ``exif_bytes`` is ``None``."""
+
if exif_bytes:
pil_img.save(destination, "jpeg", exif=exif_bytes)
else:
diff --git a/api/catalog/api/views/media_views.py b/api/catalog/api/views/media_views.py
index 9f49259e2..64d815506 100644
--- a/api/catalog/api/views/media_views.py
+++ b/api/catalog/api/views/media_views.py
@@ -168,11 +168,14 @@ class MediaViewSet(ReadOnlyModelViewSet):
def _get_user_ip(request):
"""
Read request headers to find the correct IP address.
- It is assumed that X-Forwarded-For has been sanitized by the load
- balancer and thus cannot be rewritten by malicious users.
- :param request: A Django request object.
- :return: An IP address.
+
+ It is assumed that X-Forwarded-For has been sanitized by the load balancer and
+ thus cannot be rewritten by malicious users.
+
+ :param request: a Django request object
+ :return: an IP address
"""
+
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded_for:
ip = x_forwarded_for.split(",")[0]
diff --git a/api/catalog/api/views/oauth2_views.py b/api/catalog/api/views/oauth2_views.py
index db17a03a4..c1aad087e 100644
--- a/api/catalog/api/views/oauth2_views.py
+++ b/api/catalog/api/views/oauth2_views.py
@@ -177,10 +177,7 @@ If you believe you received this message in error, please disregard it.
class VerifyEmail(APIView):
- """
- When the user follows the verification link sent to their email, enable
- their OAuth2 key.
- """
+ """Enable a user's OAuth2 key upon visiting the emailed verification link."""
swagger_schema = None
diff --git a/api/catalog/configuration/elasticsearch.py b/api/catalog/configuration/elasticsearch.py
index d32364287..af0df41ad 100644
--- a/api/catalog/configuration/elasticsearch.py
+++ b/api/catalog/configuration/elasticsearch.py
@@ -1,6 +1,4 @@
-"""
-This file contains configuration pertaining to Elasticsearch.
-"""
+"""This file contains configuration pertaining to Elasticsearch."""
from django.conf import settings
diff --git a/api/catalog/configuration/link_validation_cache.py b/api/catalog/configuration/link_validation_cache.py
index b0cdf9e6e..da6aa5118 100644
--- a/api/catalog/configuration/link_validation_cache.py
+++ b/api/catalog/configuration/link_validation_cache.py
@@ -13,9 +13,7 @@ logger = logging.getLogger(__name__)
class LinkValidationCacheExpiryConfiguration(defaultdict):
- """
- Link validation cache expiry configuration.
- """
+ """Link validation cache expiry configuration."""
SETTING_PREFIX = "LINK_VALIDATION_CACHE_EXPIRY__"
diff --git a/api/catalog/custom_auto_schema.py b/api/catalog/custom_auto_schema.py
index 6cdbc94f4..825a51234 100644
--- a/api/catalog/custom_auto_schema.py
+++ b/api/catalog/custom_auto_schema.py
@@ -6,6 +6,8 @@ from drf_yasg.utils import filter_none, force_real_str
class CustomAutoSchema(SwaggerAutoSchema):
def get_pagination_parameters(self):
"""
+ Set pagination params to an empty list.
+
Since the pagination params are a part of the ``MediaSearchRequestSerializer``,
they need not be added again as pagination params.
"""
diff --git a/api/catalog/management/commands/generatewaveforms.py b/api/catalog/management/commands/generatewaveforms.py
index 96231f646..3811ef1e9 100644
--- a/api/catalog/management/commands/generatewaveforms.py
+++ b/api/catalog/management/commands/generatewaveforms.py
@@ -9,6 +9,8 @@ from catalog.api.models.audio import Audio, AudioAddOn
def paginate_reducing_query(get_query_set, page_size=10):
"""
+ Iterate over the given query set yielding a specific number of entries each time.
+
We can't use `Paginator` because it can't handle the situation
where the query result changes each time a page is accessed.
Because the `audios` QuerySet result is naturally getting smaller
diff --git a/api/catalog/management/commands/validateopenapischema.py b/api/catalog/management/commands/validateopenapischema.py
index 913d88043..da51e424e 100644
--- a/api/catalog/management/commands/validateopenapischema.py
+++ b/api/catalog/management/commands/validateopenapischema.py
@@ -20,9 +20,8 @@ class Command(BaseCommand):
)
def handle_validation(self, spec_dict: dict):
- """
- This method should raise an error if the spec is not valid.
- """
+ """Validate the spec and raise an error if the spec is not valid."""
+
validate_spec(spec_dict, validator=openapi_v2_spec_validator)
invalid_paths = [p for p in spec_dict["paths"].keys() if not p.endswith("/")]
diff --git a/api/catalog/urls/__init__.py b/api/catalog/urls/__init__.py
index 9c96b0943..1458e2f81 100644
--- a/api/catalog/urls/__init__.py
+++ b/api/catalog/urls/__init__.py
@@ -1,4 +1,5 @@
-"""catalog URL Configuration
+"""
+This is the Openverse API URL configuration.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
diff --git a/api/test/api_live_integration.py b/api/test/api_live_integration.py
index 9495d9916..169e975a9 100644
--- a/api/test/api_live_integration.py
+++ b/api/test/api_live_integration.py
@@ -1,6 +1,7 @@
"""
-**These are the LEGACY API integration tests; do not add further tests here.**
-New tests should be added in v1_integration_test.
+These are the LEGACY API integration tests.
+
+**Do not add further tests here. New tests should be added in v1_integration_test.**
End-to-end API tests. Can be used to verify a live deployment is functioning as
designed. Run with the `pytest -s` command from this directory.
@@ -40,9 +41,8 @@ def search_fixture():
def test_search_quotes():
- """
- We want to return a response even if the user messes up quote matching.
- """
+ """Test that a response is given even if the user messes up quote matching."""
+
response = requests.get(f'{API_URL}/image/search?q="test"', verify=False)
assert response.status_code == 200
@@ -53,11 +53,13 @@ def test_search(search_fixture):
def test_search_consistency():
"""
+ Ensure that no duplicates appear in the first few pages of a search query.
+
Elasticsearch sometimes reaches an inconsistent state, which causes search
results to appear differently upon page refresh. This can also introduce
- image duplicates in subsequent pages. This test ensures that no duplicates
- appear in the first few pages of a search query.
+ image duplicates in subsequent pages.
"""
+
n_pages = 5
searches = {
requests.get(f"{API_URL}/image/search?q=honey;page={page}", verify=False)
@@ -166,9 +168,8 @@ def test_list_delete(test_list_create):
def test_license_type_filtering():
- """
- Ensure that multiple license type filters interact together correctly.
- """
+ """Ensure that multiple license type filters interact together correctly."""
+
commercial = LICENSE_GROUPS["commercial"]
modification = LICENSE_GROUPS["modification"]
commercial_and_modification = set.intersection(modification, commercial)
@@ -198,10 +199,8 @@ def test_specific_license_filter():
def test_creator_quotation_grouping():
- """
- Users should be able to group terms together with quotation marks to narrow
- down their searches more effectively.
- """
+ """Test that quotation marks can be used to narrow down search results."""
+
no_quotes = json.loads(
requests.get(
f"{API_URL}/image/search?creator=claude%20monet", verify=False
@@ -280,10 +279,12 @@ def test_watermark_preserves_exif():
def test_attribution():
"""
- The API includes an attribution string. Since there are some works where
- the title or creator is not known, the format of the attribution string
- can need to be tweaked slightly.
+ Check that the API includes an attribution string.
+
+ Since there are some works where the title or creator is not known, the format of
+ the attribution string can need to be tweaked slightly.
"""
+
title_and_creator_missing = Image(
identifier="ab80dbe1-414c-4ee8-9543-f9599312aeb8",
title=None,
@@ -347,9 +348,7 @@ def test_extension_filter():
@pytest.fixture
def search_factory():
- """
- Allows passing url parameters along with a search request.
- """
+ """Allow passing url parameters along with a search request."""
def _parameterized_search(**kwargs):
response = requests.get(f"{API_URL}/image/search", params=kwargs, verify=False)
@@ -362,9 +361,7 @@ def search_factory():
@pytest.fixture
def search_with_dead_links(search_factory):
- """
- Here we pass filter_dead = False.
- """
+ """Test with ``filter_dead`` parameter set to ``False``."""
def _search_with_dead_links(**kwargs):
return search_factory(filter_dead=False, **kwargs)
@@ -374,9 +371,7 @@ def search_with_dead_links(search_factory):
@pytest.fixture
def search_without_dead_links(search_factory):
- """
- Here we pass filter_dead = True.
- """
+ """Test with ``filter_dead`` parameter set to ``True``."""
def _search_without_dead_links(**kwargs):
return search_factory(filter_dead=True, **kwargs)
@@ -386,12 +381,12 @@ def search_without_dead_links(search_factory):
def test_page_size_removing_dead_links(search_without_dead_links):
"""
+ Test whether the number of results returned is equal to the requested page size.
+
We have about 500 dead links in the sample data and should have around
8 dead links in the first 100 results on a query composed of a single
wildcard operator.
- Test whether the number of results returned is equal to the requested
- pagesize of 100.
"""
data = search_without_dead_links(q="*", pagesize=100)
assert len(data["results"]) == 100
@@ -401,8 +396,7 @@ def test_dead_links_are_correctly_filtered(
search_with_dead_links, search_without_dead_links
):
"""
- Test the results for the same query with and without dead links are
- actually different.
+ Test the results for the same query with and without dead links are different.
We use the results' id to compare them.
"""
@@ -420,10 +414,8 @@ def test_dead_links_are_correctly_filtered(
def test_page_consistency_removing_dead_links(search_without_dead_links):
- """
- Test the results returned in consecutive pages are never repeated when
- filtering out dead links.
- """
+ """Test that results in consecutive pages don't repeat when filtering dead links."""
+
total_pages = 100
pagesize = 5
@@ -454,9 +446,7 @@ def test_related_does_not_break():
@pytest.fixture
def related_factory():
- """
- Allows passing url parameters along with a related images request.
- """
+ """Allow passing url parameters along with a related images request."""
def _parameterized_search(identifier, **kwargs):
response = requests.get(
diff --git a/api/test/api_live_search_qa.py b/api/test/api_live_search_qa.py
index d5ff9bdf6..550d341c7 100644
--- a/api/test/api_live_search_qa.py
+++ b/api/test/api_live_search_qa.py
@@ -1,8 +1,8 @@
"""
-Tests to run against a live instance of Openverse with a significant (10M+)
-number of records. Quality of search rankings can be affected by the number of
-documents in the search index, so toy examples with five or six documents
-do not accurately model relevance at scale.
+Tests to run against a live Openverse instance with a significant (10M+) record count.
+
+Quality of search rankings can be affected by the number of documents in the search
+index, so toy examples with few documents do not accurately model relevance at scale.
"""
import json
@@ -27,9 +27,12 @@ def _phrase_in_title(title, term):
def test_phrase_relevance():
"""
+ Test that results have the phrase in the tags or title.
+
If I search for "home office", the top results ought to have the phrase
'home office' in the tags or title.
"""
+
search_term = "home office"
response = requests.get(f"{API_URL}/image/search?q={search_term}", verify=False)
assert response.status_code == 200
diff --git a/api/test/audio_integration_test.py b/api/test/audio_integration_test.py
index 260ada631..6a90b146e 100644
--- a/api/test/audio_integration_test.py
+++ b/api/test/audio_integration_test.py
@@ -1,6 +1,8 @@
"""
-End-to-end API tests for audio. Can be used to verify a live deployment is
-functioning as designed. Run with the `pytest -s` command from this directory.
+End-to-end API tests for audio.
+
+Can be used to verify a live deployment is functioning as designed.
+Run with the `pytest -s` command from this directory.
"""
import json
@@ -60,6 +62,8 @@ def audio_fixture(force_result_validity):
@pytest.fixture
def jamendo_audio_fixture(force_result_validity):
"""
+ Get an audio object specifically from the Jamendo provider.
+
Thumbnail tests must use Jamendo results because the Wikimedia
sample audio results do not have thumbnails.
"""
diff --git a/api/test/backwards_compat_test.py b/api/test/backwards_compat_test.py
index 2d2f20984..fe1ebe9c8 100644
--- a/api/test/backwards_compat_test.py
+++ b/api/test/backwards_compat_test.py
@@ -1,6 +1,5 @@
"""
-This file ensures that deprecated URLs are redirected to their updated paths and
-not left to rot.
+Ensures that deprecated URLs are redirected to their updated paths and not left to rot.
Can be used to verify a live deployment is functioning as designed.
Run with the `pytest -s` command from this directory.
diff --git a/api/test/dead_link_filter_test.py b/api/test/dead_link_filter_test.py
index 773871e9c..dbca58e65 100644
--- a/api/test/dead_link_filter_test.py
+++ b/api/test/dead_link_filter_test.py
@@ -30,6 +30,8 @@ def redis(monkeypatch) -> FakeRedis:
@pytest.fixture(autouse=True)
def turn_off_db_read(monkeypatch):
"""
+ Prevent DB lookup for ES results because DB is empty.
+
Since ImageSerializer has set ``needs_db`` to ``True``, all results from ES will be
mapped to DB models. Since the test DB is empty, results array will be empty. By
patching ``needs_db`` to ``False``, we can test the dead link filtering process
@@ -165,9 +167,7 @@ def test_dead_link_filtering_all_dead_links(
@pytest.fixture
def search_factory(client):
- """
- Allows passing url parameters along with a search request.
- """
+ """Allow passing url parameters along with a search request."""
def _parameterized_search(**kwargs):
response = requests.get(f"{API_URL}/v1/images", params=kwargs, verify=False)
@@ -180,9 +180,7 @@ def search_factory(client):
@pytest.fixture
def search_without_dead_links(search_factory):
- """
- Here we pass filter_dead = True.
- """
+ """Test with ``filter_dead`` parameter set to true."""
def _search_without_dead_links(**kwargs):
return search_factory(filter_dead=True, **kwargs)
@@ -193,23 +191,21 @@ def search_without_dead_links(search_factory):
@pytest.mark.django_db
def test_page_size_removing_dead_links(search_without_dead_links):
"""
+ Test whether the number of results returned is equal to the requested page size.
+
We have about 500 dead links in the sample data and should have around
8 dead links in the first 100 results on a query composed of a single
wildcard operator.
-
- Test whether the number of results returned is equal to the requested
- page_size of 20.
"""
+
data = search_without_dead_links(q="*", page_size=20)
assert len(data["results"]) == 20
@pytest.mark.django_db
def test_page_consistency_removing_dead_links(search_without_dead_links):
- """
- Test the results returned in consecutive pages are never repeated when
- filtering out dead links.
- """
+ """Test that results in consecutive pages don't repeat when filtering dead links."""
+
total_pages = settings.MAX_PAGINATION_DEPTH
page_size = 5
diff --git a/api/test/image_integration_test.py b/api/test/image_integration_test.py
index acb5d0d44..f9e8709e1 100644
--- a/api/test/image_integration_test.py
+++ b/api/test/image_integration_test.py
@@ -1,6 +1,8 @@
"""
-End-to-end API tests for images. Can be used to verify a live deployment is
-functioning as designed. Run with the `pytest -s` command from this directory.
+End-to-end API tests for images.
+
+Can be used to verify a live deployment is functioning as designed.
+Run with the `pytest -s` command from this directory.
"""
import json
diff --git a/api/test/media_integration.py b/api/test/media_integration.py
index 7c0ac9554..ad31182ec 100644
--- a/api/test/media_integration.py
+++ b/api/test/media_integration.py
@@ -1,5 +1,6 @@
"""
Base test cases for all media types.
+
These are not tests and cannot be invoked.
"""
@@ -10,7 +11,8 @@ import requests
def search(fixture):
- """Returns results for test query."""
+ """Return results for test query."""
+
assert fixture["result_count"] > 0
@@ -40,13 +42,15 @@ def search_source_and_excluded(media_path):
def search_quotes(media_path, q="test"):
- """Returns a response when quote matching is messed up."""
+ """Return a response when quote matching is messed up."""
+
response = requests.get(f'{API_URL}/v1/{media_path}?q="{q}', verify=False)
assert response.status_code == 200
def search_quotes_exact(media_path, q):
- """Only returns exact matches for the given query"""
+ """Return only exact matches for the given query."""
+
url_format = f"{API_URL}/v1/{media_path}?q={{q}}"
unquoted_response = requests.get(url_format.format(q=q), verify=False)
assert unquoted_response.status_code == 200
@@ -66,7 +70,8 @@ def search_quotes_exact(media_path, q):
def search_special_chars(media_path, q="test"):
- """Returns a response when query includes special characters."""
+ """Return a response when query includes special characters."""
+
response = requests.get(f"{API_URL}/v1/{media_path}?q={q}!", verify=False)
assert response.status_code == 200
@@ -76,7 +81,7 @@ def search_consistency(
n_pages,
):
"""
- Returns consistent, non-duplicate results in the first n pages.
+ Return consistent, non-duplicate results in the first n pages.
Elasticsearch sometimes reaches an inconsistent state, which causes search
results to appear differently upon page refresh. This can also introduce
diff --git a/api/test/search_qa.py b/api/test/search_qa.py
index 176baee84..32416578c 100644
--- a/api/test/search_qa.py
+++ b/api/test/search_qa.py
@@ -1,6 +1,4 @@
-"""
-Perform some basic tests to ensure that search rankings work as anticipated.
-"""
+"""Perform some basic tests to ensure that search rankings work as anticipated."""
import json
import pprint
diff --git a/api/test/unit/utils/validate_images_test.py b/api/test/unit/utils/validate_images_test.py
index de89cc45c..f0af832b1 100644
--- a/api/test/unit/utils/validate_images_test.py
+++ b/api/test/unit/utils/validate_images_test.py
@@ -34,7 +34,10 @@ def test_sends_user_agent(wrapped_client_session: mock.AsyncMock):
def test_handles_timeout():
"""
- Note: This test takes just over 3 seconds to run as it simulates network delay of 3 seconds.
+ Test that case where timeout occurs.
+
+ Note: This test takes just over 3 seconds to run as it simulates network delay of
+ 3 seconds.
"""
query_hash = "test_handles_timeout"
results = [{"identifier": i} for i in range(1)]
diff --git a/api/test/v1_integration_test.py b/api/test/v1_integration_test.py
index 63038e181..d72723a41 100644
--- a/api/test/v1_integration_test.py
+++ b/api/test/v1_integration_test.py
@@ -1,6 +1,8 @@
"""
-End-to-end API tests. Can be used to verify a live deployment is functioning as
-designed. Run with the `pytest -s` command from this directory.
+End-to-end API tests.
+
+Can be used to verify a live deployment is functioning as designed.
+Run with the `pytest -s` command from this directory.
"""
import json
@@ -65,9 +67,8 @@ def test_list_delete(test_list_create):
def test_license_type_filtering():
- """
- Ensure that multiple license type filters interact together correctly.
- """
+ """Ensure that multiple license type filters interact together correctly."""
+
commercial = LICENSE_GROUPS["commercial"]
modification = LICENSE_GROUPS["modification"]
commercial_and_modification = set.intersection(modification, commercial)
@@ -97,10 +98,8 @@ def test_specific_license_filter():
def test_creator_quotation_grouping():
- """
- Users should be able to group terms together with quotation marks to narrow
- down their searches more effectively.
- """
+ """Test that quotation marks can be used to narrow down search results."""
+
no_quotes = json.loads(
requests.get(f"{API_URL}/v1/images?creator=Steve%20Wedgwood", verify=False).text
)
@@ -141,10 +140,12 @@ def test_watermark_preserves_exif():
def test_attribution():
"""
- The API includes an attribution string. Since there are some works where
- the title or creator is not known, the format of the attribution string
- can need to be tweaked slightly.
+ Check that the API includes an attribution string.
+
+ Since there are some works where the title or creator is not known, the format of
+ the attribution string can need to be tweaked slightly.
"""
+
title_and_creator_missing = Image(
identifier="ab80dbe1-414c-4ee8-9543-f9599312aeb8",
title=None,
@@ -217,9 +218,7 @@ def test_extension_filter():
@pytest.fixture
def recommendation_factory():
- """
- Allows passing url parameters along with a related images request.
- """
+ """Allow passing url parameters along with a related images request."""
def _parameterized_search(identifier, **kwargs):
response = requests.get(
diff --git a/ingestion_server/ingestion_server/api.py b/ingestion_server/ingestion_server/api.py
index 1b22d4f6c..79b7e354b 100644
--- a/ingestion_server/ingestion_server/api.py
+++ b/ingestion_server/ingestion_server/api.py
@@ -1,7 +1,4 @@
-"""
-A small RPC API server for scheduling ingestion of upstream data and
-Elasticsearch indexing tasks.
-"""
+"""A small RPC API server for scheduling data refresh and indexing tasks."""
import logging
import sys
@@ -38,8 +35,7 @@ class StatResource:
@staticmethod
def on_get(_, res, name):
"""
- Handles an incoming GET request. Provides information about the given index or
- alias.
+ Handle an incoming GET request and provides info about the given index or alias.
:param _: the incoming request
:param res: the appropriate response
@@ -54,7 +50,7 @@ class StatResource:
class BaseTaskResource:
- """Base class for all resource that need access to a task tracker"""
+ """Base class for all resource that need access to a task tracker."""
def __init__(self, tracker: TaskTracker, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -118,7 +114,7 @@ class TaskResource(BaseTaskResource):
)
def on_post(self, req, res):
"""
- Handles an incoming POST request. Schedules the specified task.
+ Handle an incoming POST request and schedule the specified task.
:param req: the incoming request
:param res: the appropriate response
@@ -219,7 +215,7 @@ class TaskResource(BaseTaskResource):
def on_get(self, _, res):
"""
- Handles an incoming GET request. Provides information about all past tasks.
+ Handle an incoming GET request and provide information about all past tasks.
:param _: the incoming request
:param res: the appropriate response
@@ -231,7 +227,7 @@ class TaskResource(BaseTaskResource):
class TaskStatus(BaseTaskResource):
def on_get(self, _, res, task_id):
"""
- Handles an incoming GET request. Provides information about a single task.
+ Handle an incoming GET request and provide information about a single task.
:param _: the incoming request
:param res: the appropriate response
@@ -249,7 +245,7 @@ class TaskStatus(BaseTaskResource):
class WorkerFinishedResource(BaseTaskResource):
def on_post(self, req, _):
"""
- Handles an incoming POST request. Records messages sent from indexer workers.
+ Handle an incoming POST request and record messages sent from indexer workers.
:param req: the incoming request
:param _: the appropriate response
@@ -301,9 +297,8 @@ class WorkerFinishedResource(BaseTaskResource):
class StateResource:
@staticmethod
def on_delete(_, __):
- """
- Forget about the last scheduled indexing job.
- """
+ """Forget about the last scheduled indexing job."""
+
clear_state()
diff --git a/ingestion_server/ingestion_server/authority.py b/ingestion_server/ingestion_server/authority.py
index 7a8ca686c..152392ee4 100644
--- a/ingestion_server/ingestion_server/authority.py
+++ b/ingestion_server/ingestion_server/authority.py
@@ -1,7 +1,8 @@
"""
-Authority is a ranking from 0 to 100 (with 0 being least authoritative)
-indicating the pedigree of an image. Some examples of things that could impact
-authority:
+Authority is a ranking indicating the pedigree of an image.
+
+It ranges from 0 (least authoritative) to 100 (most authoritative). Some examples of
+things that could impact authority are:
- The reputation of the website that posted an image
- The popularity of the uploader on a social media site in terms of number of
followers
diff --git a/ingestion_server/ingestion_server/cleanup.py b/ingestion_server/ingestion_server/cleanup.py
index d7f3b7d6e..c634e1ab5 100644
--- a/ingestion_server/ingestion_server/cleanup.py
+++ b/ingestion_server/ingestion_server/cleanup.py
@@ -1,6 +1,7 @@
"""
-Functions for processing data when it is imported into the catalog. This
-includes cleaning up malformed URLs and filtering out undesirable tags.
+Functions for processing data when it is imported into the catalog.
+
+This includes cleaning up malformed URLs and filtering out undesirable tags.
"""
import logging as log
@@ -51,7 +52,8 @@ TAG_MIN_CONFIDENCE = 0.90
def _tag_denylisted(tag):
- """Tag is banned or contains a banned substring."""
+ """Check if a tag is banned or contains a banned substring."""
+
if tag in TAG_DENYLIST:
return True
for denylisted_substring in TAG_CONTAINS_DENYLIST:
@@ -62,6 +64,8 @@ def _tag_denylisted(tag):
class CleanupFunctions:
"""
+ This class is a loose collection of static cleanup functions.
+
A cleanup function takes one parameter and returns the "cleaned" version if
an update is required, otherwise None.
@@ -71,8 +75,11 @@ class CleanupFunctions:
@staticmethod
def cleanup_url(url, tls_support):
"""
- Add protocols to the URI if they are missing, else return None.
+ Add protocols to the URI if they are missing.
+
+ :return: the URL with the protocol if an update is needed, ``None`` otherwise
"""
+
parsed = urlparse(url)
if parsed.scheme == "":
_tld = tldextract.extract(url)
@@ -94,10 +101,11 @@ class CleanupFunctions:
@staticmethod
def cleanup_tags(tags):
"""
- Delete tags because they have low accuracy or because they are in the
- denylist. If no change is made, return None.
- :return: A SQL fragment if an update is required or None
+ Delete denylisted and low-accuracy tags.
+
+ :return: an SQL fragment if an update is needed, ``None`` otherwise
"""
+
update_required = False
tag_output = []
if not tags:
@@ -148,6 +156,8 @@ _cleanup_config = {
class TlsTest:
"""
+ Test URLs to add the correct protocol when missing and use HTTPS when available.
+
URLs crawled from upstream are often lacking protocol information, or
use HTTP when HTTPS is available. We have to test a small sample of the
URLs to determine what protocol should be appended to each URL in the
@@ -228,14 +238,13 @@ def _clean_data_worker(rows, temp_table, sources_config):
def clean_image_data(table):
"""
- Data from upstream can be unsuitable for production for a number of reasons.
- Clean it up before we go live with the new data.
+ Clean up data loaded from upstream that is unsuitable for prod before going live.
:param table: The staging table for the new data
- :param upstream_db: A dict specifying the connection details of the upstream
- database.
+ :param upstream_db: A dict specifying the connection details of the upstream DB
:return: None
"""
+
# Map each table to the fields that need to be cleaned up. Then, map each
# field to its cleanup function.
log.info("Cleaning up data...")
diff --git a/ingestion_server/ingestion_server/constants/media_types.py b/ingestion_server/ingestion_server/constants/media_types.py
index eb6517bd8..4785514e2 100644
--- a/ingestion_server/ingestion_server/constants/media_types.py
+++ b/ingestion_server/ingestion_server/constants/media_types.py
@@ -1,6 +1,4 @@
-"""
-Also see `api/constants/media_types.py`
-"""
+"""Also see `api/constants/media_types.py`."""
from typing import Literal, get_args
diff --git a/ingestion_server/ingestion_server/distributed_reindex_scheduler.py b/ingestion_server/ingestion_server/distributed_reindex_scheduler.py
index f8ef4a599..562937e79 100644
--- a/ingestion_server/ingestion_server/distributed_reindex_scheduler.py
+++ b/ingestion_server/ingestion_server/distributed_reindex_scheduler.py
@@ -1,4 +1,6 @@
"""
+This module handles distributed reindexing.
+
Allocate hardware for performing a distributed index by spawning several
indexer_worker instances on multiple machines. Then, partition the work across
each worker, notifying each worker which partition to reindex through an HTTP
@@ -31,9 +33,8 @@ def schedule_distributed_index(db_conn, model_name, table_name, target_index, ta
def _assign_work(db_conn, workers, model_name, table_name, target_index):
- """
- Target index has a form of `<media_type>-<uuid>`
- """
+ """Assign jobs to workers."""
+
est_records_query = f"SELECT id FROM {table_name} ORDER BY id DESC LIMIT 1"
with db_conn.cursor() as cur:
cur.execute(est_records_query)
@@ -62,8 +63,9 @@ def _assign_work(db_conn, workers, model_name, table_name, target_index):
def _prepare_workers():
"""
- Get a list of internal URLs bound to each indexing worker. If the worker is
- stopped, start the worker.
+ Get a list of internal URLs bound to each indexing worker.
+
+ If the worker is stopped, start the worker.
:return: A list of private URLs pointing to each available indexing worker
"""
diff --git a/ingestion_server/ingestion_server/elasticsearch_models.py b/ingestion_server/ingestion_server/elasticsearch_models.py
index 8b46bc781..0397830f6 100644
--- a/ingestion_server/ingestion_server/elasticsearch_models.py
+++ b/ingestion_server/ingestion_server/elasticsearch_models.py
@@ -18,8 +18,9 @@ class RankFeature(Field):
def _verify_rank_feature(value, low, high):
"""
- Rank features must be a positive non-zero float. Our features are scaled
- from 0 to 100 for fair comparison.
+ Rank features must be a positive non-zero float.
+
+ Our features are scaled from 0 to 100 for fair comparison.
"""
if value is None or value == 0:
return None
@@ -29,10 +30,7 @@ def _verify_rank_feature(value, low, high):
class SyncableDocType(Document):
- """
- Represents tables in the source-of-truth that will be replicated to
- Elasticsearch.
- """
+ """Represents tables in the source-of-truth that will be replicated to ES."""
# Aggregations can't be performed on the _id meta-column, which
# necessitates copying it to this column in the doc. Aggregation is
@@ -42,8 +40,7 @@ class SyncableDocType(Document):
@staticmethod
def database_row_to_elasticsearch_doc(row, schema):
"""
- Children of this class must have a function mapping a Postgres model
- to an Elasticsearch document.
+ Children of this class must have a function mapping a PSQL model to an ES doc.
:param row: A tuple representing a row in Postgres.
:param schema: A map of each field name to its position in the row.
@@ -56,8 +53,9 @@ class SyncableDocType(Document):
class Media(SyncableDocType):
"""
- Represents a media object in Elasticsearch. Note that actual mappings
- are defined in `ingestion_server.es_mapping`.
+ Represents a media object in Elasticsearch.
+
+ Note that actual mappings are defined in `ingestion_server.es_mapping`.
"""
class Index:
@@ -66,8 +64,7 @@ class Media(SyncableDocType):
@staticmethod
def database_row_to_elasticsearch_doc(row: tuple, schema: dict[str, int]):
"""
- Map each row in the downstream database to a Python dictionary that
- represents a document in the ElasticSearch index.
+ Map the DB row to a Python dictionary that represents a doc in the ES index.
:param row: the database row as a tuple obtained by the psycopg2 cursor
:param schema: the mapping of database column names to the tuple index
@@ -81,8 +78,9 @@ class Media(SyncableDocType):
@staticmethod
def get_instance_attrs(row, schema):
"""
- Map the common columns in the database row to a Python dictionary that
- represents a part of the ES doc.
+ Map the common columns in the DB row to a Python dictionary.
+
+ This dictionary is a smaller part of the document indexed by Elasticsearch.
:param row: the database row as a tuple obtained by the psycopg2 cursor
:param schema: the mapping of database column names to the tuple index
@@ -137,6 +135,8 @@ class Media(SyncableDocType):
@staticmethod
def get_license_url(meta_data):
"""
+ Get license URL from the metadata.
+
If the license_url is not provided, we'll try to generate it elsewhere
from the `license` and `license_version`.
"""
@@ -149,6 +149,7 @@ class Media(SyncableDocType):
def get_maturity(meta_data, api_maturity_flag):
"""
Determine whether a work has been labeled for mature audiences only.
+
:param meta_data: The metadata column, which may have a 'mature'
flag.
:param api_maturity_flag: An API layer flag that indicates we have
@@ -199,15 +200,13 @@ class Media(SyncableDocType):
class Image(Media):
"""
- Represents an image in Elasticsearch. Note that actual mappings are defined
- in `ingestion_server.es_mapping`.
+ Represents an image in Elasticsearch.
+
+ Note that actual mappings are defined in `ingestion_server.es_mapping`.
"""
class AspectRatios(Enum):
- """
- These aspect ratios are also defined in
- ``api/catalog/api/constants/field_values.py.``
- """
+ """Also defined in ``api/catalog/api/constants/field_values.py``."""
TALL = auto()
WIDE = auto()
@@ -215,7 +214,7 @@ class Image(Media):
class ImageSizes(Enum):
"""
- Maximum threshold for each image size band
+ Maximum threshold for each image size band.
These sizes are also defined in
``api/catalog/api/constants/field_values.py.``
@@ -272,6 +271,7 @@ class Image(Media):
def get_extension(url):
"""
Get the extension from the last segment of the URL separated by a dot.
+
TODO: Use the `filetype` field once the following issue is completed:
https://github.com/WordPress/openverse-catalog/issues/536
"""
@@ -293,13 +293,14 @@ class Image(Media):
class Audio(Media):
"""
- Represents an audio in Elasticsearch. Note that actual mappings are defined
- in `ingestion_server.es_mapping`.
+ Represents an audio in Elasticsearch.
+
+ Note that actual mappings are defined in `ingestion_server.es_mapping`.
"""
class Durations(Enum):
"""
- Maximum threshold for each audio duration band
+ Maximum threshold for each audio duration band.
These durations are also defined in
``api/catalog/api/constants/field_values.py.``
diff --git a/ingestion_server/ingestion_server/es_helpers.py b/ingestion_server/ingestion_server/es_helpers.py
index ebd9dc627..98a70119b 100644
--- a/ingestion_server/ingestion_server/es_helpers.py
+++ b/ingestion_server/ingestion_server/es_helpers.py
@@ -9,9 +9,7 @@ from elasticsearch import Elasticsearch, NotFoundError, RequestsHttpConnection
class Stat(NamedTuple):
- """
- Contains information about the index or alias identified by its name.
- """
+ """Contains information about the index or alias identified by its name."""
exists: bool
is_alias: bool | None
@@ -39,8 +37,10 @@ def elasticsearch_connect(timeout: int = 300) -> Elasticsearch:
def _elasticsearch_connect() -> Elasticsearch:
"""
- Connect to an Elasticsearch indices at the configured domain. This method also
- handles AWS authentication using the AWS access key ID and the secret access key.
+ Connect to an Elasticsearch indices at the configured domain.
+
+ This method also handles AWS authentication using the AWS access key ID and the
+ secret access key.
:return: an Elasticsearch client
"""
@@ -77,8 +77,9 @@ def _elasticsearch_connect() -> Elasticsearch:
def get_stat(es: Elasticsearch, name_or_alias: str) -> Stat:
"""
- Get more information about the index name or alias given to the function. For
- any given input, the function offers three bits of information:
+ Get more information about the index name or alias given to the function.
+
+ For any given input, the function offers three bits of information:
- whether an alias or index of the name exists
- whether the name is an alias
diff --git a/ingestion_server/ingestion_server/indexer.py b/ingestion_server/ingestion_server/indexer.py
index 53e4d6cb3..5b578fc26 100644
--- a/ingestion_server/ingestion_server/indexer.py
+++ b/ingestion_server/ingestion_server/indexer.py
@@ -1,7 +1,8 @@
"""
-A utility for indexing data to Elasticsearch. For each table to
-sync, find its largest ID in database. Find the corresponding largest ID in
-Elasticsearch. If the database ID is greater than the largest corresponding
+A utility for indexing data to Elasticsearch.
+
+For each table to sync, find its largest ID in database. Find the corresponding largest
+ID in Elasticsearch. If the database ID is greater than the largest corresponding
ID in Elasticsearch, copy the missing records over to Elasticsearch.
Each table is database corresponds to an identically named index in
@@ -60,6 +61,7 @@ REP_TABLES = config(
def database_connect(autocommit=False):
"""
Repeatedly try to connect to the downstream (API) database until successful.
+
:return: A database connection object
"""
while True:
@@ -86,8 +88,8 @@ def database_connect(autocommit=False):
def get_last_item_ids(table):
"""
- Find the last item added to Postgres and return both its sequential ID
- and its UUID.
+ Find the last item added to Postgres and return both its sequential ID and UUID.
+
:param table: The name of the database table to check.
:return: A tuple containing a sequential ID and a UUID
"""
@@ -134,10 +136,8 @@ class TableIndexer:
@staticmethod
def pg_chunk_to_es(pg_chunk, columns, model_name, dest_index):
- """
- Given a list of psycopg2 results, convert them all to Elasticsearch
- documents.
- """
+ """Convert the given list of psycopg2 results to Elasticsearch documents."""
+
# Map column names to locations in the row tuple
schema = {col[0]: idx for idx, col in enumerate(columns)}
model = media_type_to_elasticsearch_model.get(model_name)
@@ -262,9 +262,7 @@ class TableIndexer:
)
def ping_callback(self):
- """
- Send a request to the callback URL indicating the completion of the task.
- """
+ """Send a request to the callback URL indicating the completion of the task."""
if not self.callback_url:
return
diff --git a/ingestion_server/ingestion_server/indexer_worker.py b/ingestion_server/ingestion_server/indexer_worker.py
index 08554d3ce..d6631b01b 100644
--- a/ingestion_server/ingestion_server/indexer_worker.py
+++ b/ingestion_server/ingestion_server/indexer_worker.py
@@ -1,6 +1,5 @@
"""
-A single worker responsible for indexing a subset of the records stored in the
-database.
+A single worker responsible for indexing a subset of the records stored in the database.
Accept an HTTP request specifying a range of image IDs to reindex. After the
data has been indexed, notify Ingestion Server and stop the instance.
@@ -99,9 +98,8 @@ def _launch_reindex(model, table, target_index, query, indexer, notify_url):
def _self_destruct():
- """
- Stop this EC2 instance once the task is finished.
- """
+ """Stop this EC2 instance once the task is finished."""
+
# Get instance ID from AWS metadata service
if config("ENVIRONMENT", default="local") == "local":
log.info("Skipping self destruction because worker is in local environment")
diff --git a/ingestion_server/ingestion_server/ingest.py b/ingestion_server/ingestion_server/ingest.py
index 887fc8b88..b4b2ffc30 100644
--- a/ingestion_server/ingestion_server/ingest.py
+++ b/ingestion_server/ingestion_server/ingest.py
@@ -57,6 +57,8 @@ RELATIVE_UPSTREAM_DB_PORT = config(
def _get_shared_cols(downstream, upstream, table: str):
"""
+ Get the common columns between two tables with the same name in different DBs.
+
Given two database connections and a table name, return the list of columns
that the two tables have in common. The upstream table has the "_view"
suffix attached to it.
@@ -80,14 +82,11 @@ def _get_shared_cols(downstream, upstream, table: str):
def _generate_indices(conn, table: str) -> tuple[list[str], dict[str, str]]:
"""
- Using the existing table as a template, generate CREATE INDEX statements for
- the new table.
+ Apply the existing table indices to the new temp table imported from upstream.
- :param conn: A connection to the API database.
- :param table: The table to be updated.
- :return: A list of CREATE INDEX statements, and a mapping from new indices to
- the previous ones.
+ :return: a list of ``CREATE INDEX`` SQL statements
"""
+
index_mapping = {}
def _clean_idxs(indices: list[str]):
@@ -139,6 +138,7 @@ def _is_foreign_key(_statement, table):
def _remap_constraint(name, con_table, fk_statement, table) -> list[SQL]:
"""Produce ALTER TABLE ... statements for each constraint."""
+
alterations = [
SQL("ALTER TABLE {con_table} DROP CONSTRAINT {name}").format(
con_table=Identifier(con_table), name=Identifier(name)
@@ -173,11 +173,13 @@ def _remap_constraint(name, con_table, fk_statement, table) -> list[SQL]:
def _generate_delete_orphans(fk_statement, fk_table):
"""
+ Parse the foreign key statement and generate the deletion statement.
+
Sometimes, upstream data is deleted. If there are foreign key
references to deleted data, we must delete them before adding
- constraints back to the table. To accomplish this, parse the
- foreign key statement and generate the deletion statement.
+ constraints back to the table.
"""
+
fk_tokens = fk_statement.split(" ")
fk_field_idx = fk_tokens.index("KEY") + 1
fk_ref_idx = fk_tokens.index("REFERENCES") + 1
@@ -201,11 +203,11 @@ def _generate_delete_orphans(fk_statement, fk_table):
def _generate_constraints(conn, table: str) -> list[SQL]:
"""
- Using the existing table as a template, generate ALTER TABLE ADD CONSTRAINT
- statements pointing to the new table.
+ Apply the existing table constraints to the new temp table imported from upstream.
- :return: A list of SQL statements.
+ :return: a list of ``ALTER TABLE ADD CONSTRAINT`` SQL statements
"""
+
# List all active constraints across the database.
get_all_constraints = SQL(
"""
@@ -254,8 +256,9 @@ def refresh_api_table(
approach: ApproachType = "advanced",
):
"""
- Import updates from the upstream catalog database into the API. The
- process involves the following steps.
+ Import updates from the upstream catalog database into the API.
+
+ The process involves the following steps.
1. Get the list of overlapping columns: ``_get_shared_cols``
2. Create the FDW extension if it does not exist
@@ -342,6 +345,8 @@ def promote_api_table(
progress: multiprocessing.Value = None,
):
"""
+ Promote the temporary table in the API database to the main one.
+
This runs after ``refresh_api_table``. The process involves the following steps.
6. Recreate indices from the original table: ``_generate_indices``
diff --git a/ingestion_server/ingestion_server/qa.py b/ingestion_server/ingestion_server/qa.py
index ad3210ec0..d24c289d1 100644
--- a/ingestion_server/ingestion_server/qa.py
+++ b/ingestion_server/ingestion_server/qa.py
@@ -54,9 +54,7 @@ def _test_audio(title, tags, creator, relevance):
def _phrase_relevance_images(index):
- """
- Creates documents for images with varying relevance in the given index.
- """
+ """Create documents for images with varying relevance in the given index."""
less_relevant_1 = _test_image(
title="A picture of my office",
@@ -93,9 +91,7 @@ def _phrase_relevance_images(index):
def _phrase_relevance_audio(index):
- """
- Creates documents for audio with varying relevance in the given index.
- """
+ """Create documents for audio with varying relevance in the given index."""
less_relevant_1 = _test_audio(
title="Symphony No. 1 in C major, Op. 21",
diff --git a/ingestion_server/ingestion_server/queries.py b/ingestion_server/ingestion_server/queries.py
index 57fa865ec..54f14f846 100644
--- a/ingestion_server/ingestion_server/queries.py
+++ b/ingestion_server/ingestion_server/queries.py
@@ -8,8 +8,10 @@ from ingestion_server.constants.internal_types import ApproachType
def get_existence_queries(model: str, table: str = None) -> tuple[SQL, SQL]:
"""
- Get the query for checking whether an identifier exists in the deleted or
- the mature tables for the media. The media tables are assumed to be named
+ Get the query for checking whether a media is deleted or mature.
+
+ Returns two SQL queries for checking if an identifier exists in the deleted or the
+ mature tables for the media respectively. The media tables are assumed to be named
with the prefixes "api_deleted" and "api_mature" respectively.
:param model: the name to use for the deleted and mature tables
@@ -50,9 +52,10 @@ def get_fdw_query(
host: str, port: int, dbname: str, user: str, password: str, table: str
):
"""
- Get the query for creating a new FDW to be used when copying data from the
- upstream DB to the downstream DB. It creates a new schema named "upstream"
- in which the upstream table can be accessed.
+ Get the query for creating a new FDW from the upstream DB to the downstream DB.
+
+ This FDW will be used when copying data. It creates a new schema named "upstream"
+ in the downstream DB through which the upstream table can be accessed.
:param host: the hostname of the upstream DB relative to the downstream
:param port: the exposed port of the upstream DB accessible from downstream
@@ -95,11 +98,12 @@ def get_copy_data_query(
limit: int | None = 100_000,
):
"""
- Get the query for copying data from the upstream table to a temporary table
- in the downstream database. This temporary table will replace the permanent
- one later on. This query uses the "temp_import_" prefix on the temporary
- table and avoids entries from the deleted table with the "api_deleted"
- prefix. After the copying process, the "upstream" schema is dropped.
+ Get the query for copying data from an upstream table to a temp downstream table.
+
+ This temporary table in the downstream DB will eventually replace the permanent one.
+ This query uses the "temp_import_" prefix on the temporary table and avoids entries
+ from the deleted table with the "api_deleted" prefix. After the copying process,
+ the "upstream" schema is dropped and the FDW is closed.
When running this on a non-production environment, the results will be ordered
by `identifier` to simulate a random sample and only the first 100k records
@@ -208,8 +212,9 @@ def get_copy_data_query(
def get_go_live_query(table: str, index_mapping: dict[str, str]):
"""
- Get the query for replacing the old table with new temporary table. The
- temporary table with the "temp_import_" prefix replaces the un-prefixed
+ Get the query for replacing the old table with new temporary table.
+
+ The temporary table with the "temp_import_" prefix replaces the un-prefixed
old table.
:param table: the name of the old table being replaced with the temp
diff --git a/ingestion_server/ingestion_server/state.py b/ingestion_server/ingestion_server/state.py
index 57ec25e0d..8213c6769 100644
--- a/ingestion_server/ingestion_server/state.py
+++ b/ingestion_server/ingestion_server/state.py
@@ -1,4 +1,6 @@
"""
+Handles operations pertaining to the state of indexe workers.
+
Indexing is distributed across multiple independent hosts. We don't want to
"go live" in production with the newly indexed data until all of the indexing
workers have finished their tasks. To that end, we need to track the state of
@@ -37,8 +39,7 @@ class TaskData(NamedTuple):
def register_indexing_job(worker_ips, target_index, task_id):
"""
- Track the hosts that are running indexing jobs. Only one indexing job can
- run at a time.
+ Track the active indexer workers to prevent concurrent indexing jobs.
:param worker_ips: A list of private IP addresses corresponding to the pool
of relevant indexer-worker instances.
@@ -71,8 +72,8 @@ def register_indexing_job(worker_ips, target_index, task_id):
def worker_finished(worker_ip, error):
"""
- The scheduler received a notification indicating an indexing worker has
- finished its task.
+ Receive the notifications indicating an indexing worker has finished its task.
+
:param worker_ip: The private IP of the worker.
:param error: Whether this worker had an error during processing.
:return: TaskData namedtuple containing the target index, task_id, and the
@@ -109,9 +110,8 @@ def worker_finished(worker_ip, error):
def clear_state():
- """
- Forget about all running index jobs. Use with care.
- """
+ """Forget about all running index jobs. Use with care."""
+
with FileLock(lock_path), shelve.open(shelf_path, writeback=True) as db:
for key in db:
log.info("Deleting " + str(db[key]))
diff --git a/ingestion_server/ingestion_server/tasks.py b/ingestion_server/ingestion_server/tasks.py
index f628f6525..d801ace89 100644
--- a/ingestion_server/ingestion_server/tasks.py
+++ b/ingestion_server/ingestion_server/tasks.py
@@ -1,6 +1,4 @@
-"""
-Simple in-memory tracking of executed tasks.
-"""
+"""Simple in-memory tracking of executed tasks."""
import datetime
import logging
@@ -18,8 +16,9 @@ class TaskTypes(Enum):
@staticmethod
def _generate_next_value_(name: str, *args, **kwargs) -> str:
"""
- Generates the value for ``auto()`` given the name of the enum item. Therefore,
- this function must be defined before any of the enum items.
+ Generate the value for ``auto()`` given the name of the enum item.
+
+ Therefore, this function must be defined before any of the enum items.
:param name: the enum variable name
:return: the enum value
@@ -57,8 +56,9 @@ class TaskTypes(Enum):
def __str__(self):
"""
- Get the string representation of this enum. Unlike other objects, this
- does not default to ``__repr__``.
+ Get the string representation of this enum.
+
+ Unlike other objects, this does not default to ``__repr__``.
:return: the string representation
"""
@@ -77,6 +77,7 @@ class TaskTracker:
def add_task(self, task_id: str, **kwargs):
"""
Store information about a new task in memory.
+
:param task: the task being performed
:param task_id: the UUID of the task
"""
@@ -91,6 +92,7 @@ class TaskTracker:
def serialize_task_info(task_info: dict) -> dict:
"""
Generate a response dictionary containing all relevant information about a task.
+
:param task_info: the stored information about the task
:return: the details of the task to show to the user
"""
@@ -98,6 +100,7 @@ class TaskTracker:
def _time_fmt(timestamp: int) -> str | None:
"""
Format the timestamp into a human-readable date and time notation.
+
:param timestamp: the timestamp to format
:return: the human-readable form of the timestamp
"""
@@ -129,6 +132,7 @@ class TaskTracker:
def list_task_statuses(self) -> list:
"""
Get the statuses of all tasks.
+
:return: the statuses of all tasks
"""
@@ -139,6 +143,7 @@ class TaskTracker:
def get_task_status(self, task_id) -> dict:
"""
Get the status of a single task with the given task ID.
+
:param task_id: the ID of the task to get the status for
:return: the status of the task
"""
@@ -161,9 +166,9 @@ def perform_task(
**kwargs,
):
"""
- Perform the task defined by the API request by invoking the task function with the
- correct arguments. Any additional keyword arguments will be forwarded to the
- appropriate task functions.
+ Perform the requested task by invoking the task function with the correct arguments.
+
+ Any additional keyword arguments will be forwarded to the task functions.
:param task_id: the UUID assigned to the task for tracking
:param model: the media type for which the action is being performed
diff --git a/ingestion_server/test/gen_integration_compose.py b/ingestion_server/test/gen_integration_compose.py
index 74f1282b4..d3ba094b7 100644
--- a/ingestion_server/test/gen_integration_compose.py
+++ b/ingestion_server/test/gen_integration_compose.py
@@ -1,6 +1,5 @@
"""
-Parses the top-level Docker Compose file and generates a Docker Compose file for
-the integration tests.
+Parses the top-level Docker Compose file and generates one for the integration tests.
The generated file is written to the same directory this script resides in with
the name ``integration-docker-compose.yml``.
@@ -27,8 +26,10 @@ dest_dc_path = this_dir.joinpath("integration-docker-compose.yml")
def _prune_services(conf: dict):
"""
- Prune the unnecessary services from the Docker Compose configuration,
- keeping only those that are used in the integration tests.
+ Prune the unnecessary services from the Docker Compose configuration.
+
+ After this step, only those that are used in the integration tests are left.
+
:param conf: the Docker Compose configuration
"""
@@ -40,8 +41,11 @@ def _prune_services(conf: dict):
def _map_ports(conf: dict):
"""
- Change the port mappings for the services so as to not conflict any running
- containers that might be using those ports.
+ Change the port mappings for the services to avoid conflicts.
+
+ This ensures that the test containers do not use the same ports as dev containers
+ that might already be using them.
+
:param conf: the Docker Compose configuration
"""
@@ -60,8 +64,10 @@ def _map_ports(conf: dict):
def _fixup_env(conf: dict):
"""
- Change the relative paths to the environment files to absolute paths so that
- they hold up in the new Docker Compose file.
+ Change the relative paths to the environment files to absolute paths.
+
+ This ensures that they are point to valid locations in the new Docker Compose file.
+
:param conf: the Docker Compose configuration
"""
@@ -75,8 +81,10 @@ def _fixup_env(conf: dict):
def _remove_volumes(conf: dict):
"""
- Remove the volumes from the compose configuration so that the images begin with
- a fresh start on every startup.
+ Remove the volumes from the compose configuration.
+
+ This ensures that the images begin with a fresh start on every startup.
+
:param conf: the Docker Compose configuration
"""
volumes_to_remove = {
@@ -95,8 +103,8 @@ def _remove_volumes(conf: dict):
def _change_directories(conf: dict):
"""
- Update the relative paths of the directories such as build context or bind
- volumes attached to the containers.
+ Update the relative paths of the directories like build context or bind volumes.
+
:param conf: the Docker Compose configuration
"""
@@ -109,8 +117,8 @@ def _change_directories(conf: dict):
def _rename_services(conf: dict):
"""
- Add the 'integration_' prefix to the services to distinguish them from the
- normal services running in dev environments.
+ Add the 'integration_' prefix to the services to distinguish them from dev services.
+
:param conf: the Docker Compose configuration
"""
diff --git a/ingestion_server/test/integration_test.py b/ingestion_server/test/integration_test.py
index 9e0105b02..e270ceda1 100644
--- a/ingestion_server/test/integration_test.py
+++ b/ingestion_server/test/integration_test.py
@@ -1,7 +1,8 @@
"""
-Integration test for the ingestion-server. Spins up Docker containers, loads
-1000 images into the upstream database, and ensures that the data has been
-copied and indexed downstream.
+Integration test for the ingestion-server.
+
+This test spins up Docker containers, loads media items into the upstream database, and
+ensures that the data has been copied and indexed downstream.
"""
import logging
@@ -67,6 +68,7 @@ class TestIngestion(unittest.TestCase):
def _wait_for_dbs(cls):
"""
Wait for databases to come up and establish connections to both.
+
:return: the connections to the upstream and downstream databases
"""
@@ -106,8 +108,8 @@ class TestIngestion(unittest.TestCase):
@classmethod
def _wait(cls, cmd):
"""
- Run the given long running command in a subprocess and block while that
- command executes.
+ Run the given long-running command in a subprocess and block while it runs.
+
:param cmd: the long-running command to execute in a subprocess
"""
@@ -120,9 +122,7 @@ class TestIngestion(unittest.TestCase):
@classmethod
def _wait_for_es(cls) -> None:
- """
- Wait for Elasticsearch to come up.
- """
+ """Wait for Elasticsearch to come up."""
logging.info("Waiting for ES to be ready...")
port = service_ports["es"]
@@ -131,9 +131,7 @@ class TestIngestion(unittest.TestCase):
@classmethod
def _wait_for_ing(cls) -> None:
- """
- Wait for ingestion-server to come up.
- """
+ """Wait for ingestion-server to come up."""
logging.info("Waiting for ingestion-server to be ready...")
port = service_ports["ingestion_server"]
@@ -167,6 +165,7 @@ class TestIngestion(unittest.TestCase):
def _get_index_parts(index: str, table: str) -> list[str]:
"""
Strip out common keywords from the index to get a the name & columns.
+
Indices take the form of:
CREATE [UNIQUE] INDEX {name} ON {table} USING btree {columns}
Output will look like: ["my_special_index", "(my_column)"]
@@ -185,9 +184,8 @@ class TestIngestion(unittest.TestCase):
@classmethod
def _get_indices(cls, conn, table) -> dict[str, str]:
- """
- Get the indices on a given table using a given connection.
- """
+ """Get the indices on a given table using a given connection."""
+
index_sql = f"SELECT indexdef FROM pg_indexes WHERE tablename = '{table}';"
with conn.cursor() as cursor:
cursor.execute(index_sql)
@@ -197,9 +195,8 @@ class TestIngestion(unittest.TestCase):
@classmethod
def _get_constraints(cls, conn, table) -> dict[str, str]:
- """
- Get the constraints on a given table using a given connection.
- """
+ """Get the constraints on a given table using a given connection."""
+
constraint_sql = f"""
SELECT conname, pg_get_constraintdef(c.oid)
FROM pg_constraint AS c
@@ -218,10 +215,8 @@ class TestIngestion(unittest.TestCase):
assert es.indices.get(index=index_name) is not None
def _ingest_upstream(self, model, suffix="integration"):
- """
- Check that INGEST_UPSTREAM task completes successfully and responds
- with a callback.
- """
+ """Check that INGEST_UPSTREAM task succeeds and responds with a callback."""
+
before_indices = self._get_indices(self.downstream_db, model)
before_constraints = self._get_constraints(self.downstream_db, model)
req = {
@@ -248,10 +243,8 @@ class TestIngestion(unittest.TestCase):
), "Constraints in DB don't match the names they had before the go-live"
def _promote(self, model, suffix="integration", alias=None):
- """
- Check that PROMOTE task completes successfully and configures alias mapping
- in Elasticsearch.
- """
+ """Check that PROMOTE task succeeds and configures alias mapping in ES."""
+
if alias is None:
alias = model
req = {
@@ -299,11 +292,14 @@ class TestIngestion(unittest.TestCase):
self, model, alias, suffix="integration", omit_force_delete=False
):
"""
+ Send a soft delete request.
+
Deleting without the ``force_delete`` flag set to ``True`` is
considered a soft-delete because it will be declined if the target is
an alias. Not providing the flag is equivalent to setting it to
``False``.
"""
+
req = {
"model": model,
"action": "DELETE_INDEX",
@@ -442,9 +438,10 @@ class TestIngestion(unittest.TestCase):
@pytest.mark.order(8)
def test_upstream_indexed_images(self):
"""
- Check that the image data has been successfully indexed in
- Elasticsearch. The number of hits for a blank search should match the
- size of the loaded mock data.
+ Check that the image data has been successfully indexed in Elasticsearch.
+
+ The number of hits for a blank search should match the size of the loaded mock
+ data.
"""
es = self._get_es()
@@ -456,9 +453,10 @@ class TestIngestion(unittest.TestCase):
@pytest.mark.order(9)
def test_upstream_indexed_audio(self):
"""
- Check that the audio data has been successfully indexed in
- Elasticsearch. The number of hits for a blank search should match the
- size of the loaded mock data.
+ Check that the audio data has been successfully indexed in Elasticsearch.
+
+ The number of hits for a blank search should match the size of the loaded mock
+ data.
"""
es = self._get_es()
@@ -469,10 +467,8 @@ class TestIngestion(unittest.TestCase):
@pytest.mark.order(10)
def test_update_index_images(self):
- """
- Check that the image data can be updated from the API database into
- Elasticsearch.
- """
+ """Check that the image data can be updated from the API database into ES."""
+
req = {
"model": "image",
"action": "UPDATE_INDEX",
@@ -489,10 +485,8 @@ class TestIngestion(unittest.TestCase):
@pytest.mark.order(11)
def test_update_index_audio(self):
- """
- Check that the audio data can be updated from the API database into
- Elasticsearch.
- """
+ """Check that the audio data can be updated from the API database into ES."""
+
req = {
"model": "audio",
"action": "UPDATE_INDEX",
diff --git a/ingestion_server/test/unit_tests/conftest.py b/ingestion_server/test/unit_tests/conftest.py
index a79a07b10..23be07a8e 100644
--- a/ingestion_server/test/unit_tests/conftest.py
+++ b/ingestion_server/test/unit_tests/conftest.py
@@ -6,14 +6,15 @@ from ingestion_server.elasticsearch_models import Audio, Image
def create_mock_audio(override=None):
"""
- Produce a mock audio. Override default fields by passing in a dict with the
- desired keys and values.
+ Produce a mock audio.
+ Override default fields by passing in a dict with the desired keys and values.
For example, to make an image with a custom title and default everything
else:
>>> create_mock_audio({'title': 'My title'})
:return:
"""
+
test_popularity = {"downloads": 3}
license_url = "http://creativecommons.org/publicdomain/zero/1.0/"
meta_data = {"popularity_metrics": test_popularity, "license_url": license_url}
@@ -65,14 +66,15 @@ def create_mock_audio(override=None):
def create_mock_image(override=None):
"""
- Produce a mock image. Override default fields by passing in a dict with the
- desired keys and values.
+ Produce a mock image.
+ Override default fields by passing in a dict with the desired keys and values.
For example, to make an image with a custom title and default everything
else:
>>> create_mock_image({'title': 'My title'})
:return:
"""
+
test_popularity = {"views": 50, "likes": 3, "comments": 1}
license_url = "https://creativecommons.org/licenses/by/2.0/fr/legalcode"
meta_data = {"popularity_metrics": test_popularity, "license_url": license_url}