Compare commits

...

2 Commits

Author SHA1 Message Date
abab9b359f Add custom 404 and 500 error handlers with corresponding templates
All checks were successful
Ruff / ruff (push) Successful in 10s
2025-05-02 04:28:03 +02:00
f5a874c6df Remove unused utility functions from models_utils.py 2025-05-02 03:38:11 +02:00
5 changed files with 60 additions and 114 deletions

View File

@ -1,112 +0,0 @@
from __future__ import annotations
import logging
from datetime import datetime
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from django.db import models
logger: logging.Logger = logging.getLogger(__name__)
def wrong_typename(data: dict, expected: str) -> bool:
"""Check if the data is the expected type.
# TODO(TheLovinator): Double check this. # noqa: TD003
Type name examples:
- Game
- DropCampaign
- TimeBasedDrop
- DropBenefit
- RewardCampaign
- Reward
Args:
data (dict): The data to check.
expected (str): The expected type.
Returns:
bool: True if the data is not the expected type.
"""
is_unexpected_type: bool = data.get("__typename", "") != expected
if is_unexpected_type:
logger.error("Not a %s? %s", expected, data)
return is_unexpected_type
def update_field(instance: models.Model, django_field_name: str, new_value: str | datetime | None) -> int:
"""Update a field on an instance if the new value is different from the current value.
Args:
instance (models.Model): The Django model instance.
django_field_name (str): The name of the field to update.
new_value (str | datetime | None): The new value to update the field with.
Returns:
int: If the field was updated, returns 1. Otherwise, returns 0.
"""
# Get the current value of the field.
try:
current_value = getattr(instance, django_field_name)
except AttributeError:
logger.exception("Field %s does not exist on %s", django_field_name, instance)
return 0
# Only update the field if the new value is different from the current value.
if new_value and new_value != current_value:
setattr(instance, django_field_name, new_value)
return 1
# 0 fields updated.
return 0
def get_value(data: dict, key: str) -> datetime | str | None:
"""Get a value from a dictionary.
We have this function so we can handle values that we need to convert to a different type. For example, we might
need to convert a string to a datetime object.
Args:
data (dict): The dictionary to get the value from.
key (str): The key to get the value for.
Returns:
datetime | str | None: The value from the dictionary
"""
data_key: Any | None = data.get(key)
if not data_key:
logger.warning("Key %s not found in %s", key, data)
return None
# Dates are in the format "2024-08-12T05:59:59.999Z"
dates: list[str] = ["endAt", "endsAt,", "startAt", "startsAt", "createdAt", "earnableUntil"]
if key in dates:
logger.debug("Converting %s to datetime", data_key)
return datetime.fromisoformat(data_key)
return data_key
def update_fields(instance: models.Model, data: dict, field_mapping: dict[str, str]) -> int:
"""Update multiple fields on an instance using a mapping from external field names to model field names.
Args:
instance (models.Model): The Django model instance.
data (dict): The new data to update the fields with.
field_mapping (dict[str, str]): A dictionary mapping external field names to model field names.
Returns:
int: The number of fields updated. Used for only saving the instance if there were changes.
"""
dirty = 0
for json_field, django_field_name in field_mapping.items():
data_key: datetime | str | None = get_value(data, json_field)
dirty += update_field(instance=instance, django_field_name=django_field_name, new_value=data_key)
if dirty > 0:
instance.save()
return dirty

14
core/templates/404.html Normal file
View File

@ -0,0 +1,14 @@
{% extends "base.html" %}
{% block content %}
<div class="row justify-content-center">
<div class="col-md-8 text-center">
<div class="alert-danger mt-5">
<h1 class="display-1">404</h1>
<h2>Page Not Found</h2>
<p class="lead">The page you're looking for doesn't exist or has been moved.</p>
<p>Check the URL or return to the <a href="{% url 'index' %}" class="alert-link">homepage</a>.</p>
</div>
</div>
</div>
{% endblock content %}

14
core/templates/500.html Normal file
View File

@ -0,0 +1,14 @@
{% extends "base.html" %}
{% block content %}
<div class="row justify-content-center">
<div class="col-md-8 text-center">
<div class="alert-danger mt-5">
<h1 class="display-1">500</h1>
<h2>Internal Server Error</h2>
<p class="lead">An unexpected error occurred while processing your request.</p>
<p>Check the URL or return to the <a href="{% url 'index' %}" class="alert-link">homepage</a>.</p>
</div>
</div>
</div>
{% endblock content %}

View File

@ -8,8 +8,8 @@ from core.views import get_game, get_games, get_home
app_name: str = "core"
# TODO(TheLovinator): Add a 404 page and a 500 page.
# https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
handler404 = "core.views.handler404"
handler500 = "core.views.handler500"
# TODO(TheLovinator): Add a robots.txt file.
# https://developers.google.com/search/docs/crawling-indexing/robots/intro

View File

@ -19,6 +19,36 @@ if TYPE_CHECKING:
logger: logging.Logger = logging.getLogger(__name__)
def handler404(request: HttpRequest, exception: Exception | None = None) -> HttpResponse:
"""Custom 404 error handler.
Args:
request (HttpRequest): The request object that caused the 404.
exception (Exception, optional): The exception that caused the 404. Defaults to None.
Returns:
HttpResponse: The rendered 404 template.
"""
logger.warning(
"404 error occurred",
extra={"path": request.path, "exception": str(exception) if exception else None},
)
return render(request=request, template_name="404.html", status=404)
def handler500(request: HttpRequest) -> HttpResponse:
"""Custom 500 error handler.
Args:
request (HttpRequest): The request object that caused the 500.
Returns:
HttpResponse: The rendered 500 template.
"""
logger.error("500 error occurred", extra={"path": request.path})
return render(request=request, template_name="500.html", status=500)
@require_http_methods(request_method_list=["GET", "HEAD"])
def get_home(request: HttpRequest) -> HttpResponse:
"""Render the index page with drops grouped hierarchically by game and campaign.