Skip to content

Commit

Permalink
Clean up types in django_unicorn/
Browse files Browse the repository at this point in the history
  • Loading branch information
epw1624 authored and adamghill committed Jul 25, 2024
1 parent fdff617 commit d245d2c
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 23 deletions.
9 changes: 6 additions & 3 deletions django_unicorn/cacher.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging
import pickle
from typing import List
from typing import Dict, List, Optional

from django.core.cache import caches
from django.http import HttpRequest
Expand Down Expand Up @@ -28,7 +28,7 @@ class CacheableComponent:
"""

def __init__(self, component: "django_unicorn.views.UnicornView"):
self._state = {}
self._state: Dict = {}
self.cacheable_component = component

def __enter__(self):
Expand Down Expand Up @@ -120,7 +120,10 @@ def cache_full_tree(component: "django_unicorn.views.UnicornView"):
cache.set(_component.component_cache_key, _component)


def restore_from_cache(component_cache_key: str, request: HttpRequest = None) -> "django_unicorn.views.UnicornView":
def restore_from_cache(
component_cache_key: str,
request: Optional[HttpRequest] = None
) -> "django_unicorn.views.UnicornView":
"""
Gets a cached unicorn view by key, restoring and getting cached parents and children
and setting the request.
Expand Down
8 changes: 4 additions & 4 deletions django_unicorn/call_method_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def parse_kwarg(kwarg: str, *, raise_if_unparseable=False) -> Dict[str, Any]:
# context when the templatetag is rendered, so just return the expr
# as a string.
value = _get_expr_string(assign.value)
return {target.id: value}
return {target.id: value} #type: ignore
else:
raise InvalidKwargError(f"'{kwarg}' is invalid")
except SyntaxError as e:
Expand All @@ -128,7 +128,7 @@ def parse_kwarg(kwarg: str, *, raise_if_unparseable=False) -> Dict[str, Any]:
@lru_cache(maxsize=128, typed=True)
def parse_call_method_name(
call_method_name: str,
) -> Tuple[str, Tuple[Any], Mapping[str, Any]]:
) -> Tuple[str, Tuple[Any, ...], Mapping[str, Any]]:
"""
Parses the method name from the request payload into a set of parameters to pass to
a method.
Expand All @@ -152,10 +152,10 @@ def parse_call_method_name(
method_name = method_name[1:]

tree = ast.parse(method_name, "eval")
statement = tree.body[0].value
statement = tree.body[0].value #type: ignore

if tree.body and isinstance(statement, ast.Call):
call = tree.body[0].value
call = tree.body[0].value # type: ignore
method_name = call.func.id
args = [eval_value(arg) for arg in call.args]
kwargs = {kw.arg: eval_value(kw.value) for kw in call.keywords}
Expand Down
8 changes: 4 additions & 4 deletions django_unicorn/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
try:
from pydantic import BaseModel as PydanticBaseModel
except ImportError:
PydanticBaseModel = None
PydanticBaseModel = None # type: ignore


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -188,7 +188,7 @@ def _get_model_dict(model: Model) -> dict:

# Set `pk` for models that subclass another model which only have `id` set
if not model_pk:
model_json["pk"] = model.pk or model.id
model_json["pk"] = model.pk or model.id #type: ignore

# Add in m2m fields
m2m_field_names = _get_many_to_many_field_related_names(model)
Expand Down Expand Up @@ -235,7 +235,7 @@ def _json_serializer(obj):
queryset_json.append(model_json)

return queryset_json
elif PydanticBaseModel and isinstance(obj, PydanticBaseModel):
elif PydanticBaseModel and isinstance(obj, PydanticBaseModel): #type: ignore
return obj.dict()
elif isinstance(obj, Decimal):
return str(obj)
Expand Down Expand Up @@ -352,7 +352,7 @@ def _dumps(
serialized_data: bytes,
*,
fix_floats: bool = True,
exclude_field_attributes: Optional[Tuple[str, ...]] = None,
exclude_field_attributes: Optional[Tuple[str]] = None,
sort_dict: bool = True,
) -> Dict:
"""
Expand Down
18 changes: 10 additions & 8 deletions django_unicorn/typer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from dataclasses import is_dataclass
from datetime import date, datetime, time, timedelta, timezone
from inspect import signature
from typing import Dict, List, Union
from typing import Any, Dict, List, Optional, Tuple, Union
from typing import get_type_hints as typing_get_type_hints
from uuid import UUID

Expand Down Expand Up @@ -32,13 +32,15 @@ def _check_pydantic(cls) -> bool: # noqa: ARG001
from typing import get_args, get_origin
except ImportError:
# Fallback to dunder methods for older versions of Python
def get_args(type_hint):
if hasattr(type_hint, "__args__"):
return type_hint.__args__

def get_origin(type_hint):
if hasattr(type_hint, "__origin__"):
return type_hint.__origin__
def get_args(tp: Any) -> Tuple[Any, ...]:
if hasattr(tp, "__args__"):
return tp.__args__
return ()

def get_origin(tp: Any) -> Optional[Any]:
if hasattr(tp, "__origin__"):
return tp.__origin__
return None


try:
Expand Down
10 changes: 6 additions & 4 deletions django_unicorn/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from django.conf import settings
from django.template import engines
from django.template.backends.django import Template
from django.utils.html import _json_script_escapes
from django.utils.html import _json_script_escapes # type: ignore
from django.utils.safestring import SafeText, mark_safe

try:
Expand All @@ -33,13 +33,15 @@ def generate_checksum(data: Union[bytes, str, Dict]) -> str:
The generated checksum.
"""

data_bytes = data
data_bytes: Optional[bytes] = None

if isinstance(data, dict):
if isinstance(data, bytes):
data_bytes = data
elif isinstance(data, dict):
data_bytes = str.encode(str(data))
elif isinstance(data, str):
data_bytes = str.encode(data)
elif not isinstance(data, bytes):
else:
raise TypeError(f"Invalid type: {type(data)}")

checksum = hmac.new(
Expand Down
12 changes: 12 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,18 @@ ignore_missing_imports = true
module="cachetools.*"
ignore_missing_imports = true

[[tool.mypy.overrides]]
module = "django_unicorn.cacher"
disable_error_code = ["name-defined"]

[[tool.mypy.overrides]]
module = "django_unicorn.typing"
disable_error_code = ["empty-body"]

[[tool.mypy.overrides]]
module = "decorator"
ignore_missing_imports = true

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

0 comments on commit d245d2c

Please sign in to comment.