Skip to content

Commit

Permalink
Maintenance update
Browse files Browse the repository at this point in the history
  • Loading branch information
MrThearMan committed Oct 26, 2023
1 parent c901ead commit 43261ce
Show file tree
Hide file tree
Showing 20 changed files with 496 additions and 415 deletions.
1 change: 1 addition & 0 deletions .github/ISSUE_TEMPLATE/bug_report.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ body:
description: >-
Please note that python versions not available below are not supported.
options:
- "3.12"
- "3.11"
- "3.10"
- "3.9"
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ jobs:
test:
uses: MrThearMan/CI/.github/workflows/[email protected]
with:
python-version: '["3.8", "3.9", "3.10", "3.11"]'
python-version: '["3.8", "3.9", "3.10", "3.11", "3.12"]'
10 changes: 3 additions & 7 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,8 @@ repos:
"--markdown-linebreak-ext=md"
]

- repo: https://github.com/psf/black
rev: 23.10.0
hooks:
- id: black

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.1
rev: v0.1.2
hooks:
- id: ruff
- id: ruff
- id: ruff-format
33 changes: 12 additions & 21 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
export DJANGO_SETTINGS_MODULE = tests.django.settings
export DJANGO_SETTINGS_MODULE = tests.project.settings

.PHONY: help
.PHONY: dev
.PHONY: docs
.PHONY: translations
.PHONY: tests
.PHONY: test
.PHONY: tox
.PHONY: hook
.PHONY: pre-commit
.PHONY: pre-commit-update
.PHONY: lint
.PHONY: mypy
.PHONY: Makefile

Expand All @@ -27,13 +25,13 @@ define helptext

dev Serve manual testing server
docs Serve mkdocs for development.
translations Make and compile translations.
tests Run all tests with coverage.
test <name> Run all tests maching the given <name>
tox Run all tests with tox.
hook Install pre-commit hook.
pre-commit Run pre-commit hooks on all files.
pre-commit-update Update all pre-commit hooks to latest versions.
lint Run pre-commit hooks on all files.
migrate Run migrations.
migrations Create migrations.
mypy Run mypy on all files.

Use quotes (" ") if command contains flags (-h / --help)
Expand All @@ -50,16 +48,6 @@ dev:
docs:
@poetry run mkdocs serve -a localhost:8080

translations:
@echo ""
@echo Making translations...
@poetry run python manage.py makemessages -l fi --ignore=.venv/* --ignore=.tox/*
@echo ""
@echo Compiling...
@poetry run python manage.py compilemessages --ignore=.venv/* --ignore=.tox/*
@echo ""
@echo Done!

tests:
@poetry run coverage run -m pytest -vv -s --log-cli-level=INFO

Expand All @@ -72,11 +60,14 @@ tox:
hook:
@poetry run pre-commit install

pre-commit:
@poetry run pre-commit run --all-files
migrate:
@poetry run python manage.py migrate

pre-commit-update:
@poetry run pre-commit autoupdate
migrations:
@poetry run python manage.py makemigrations

lint:
@poetry run pre-commit run --all-files

mypy:
@poetry run mypy admin_data_views/
14 changes: 9 additions & 5 deletions admin_data_views/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,23 @@ def get_data_admin_views() -> AppDict:

def download_file(request: HttpRequest) -> HttpResponse: # pragma: no cover
if request.method.upper() != "POST":
return HttpResponse(status=405, content=f"{request.method} not supported.", headers={"Allow": "POST"})
return HttpResponse(
status=405,
content=f"{request.method} not supported.",
headers={"Allow": "POST"},
)

try:
name: str = request.POST["name"] # type: ignore
name: str = request.POST["name"] # type: ignore[assignment]
except KeyError:
return HttpResponse(status=400, content="'name' is required.")

try:
data: str = request.POST["data"] # type: ignore
data: str = request.POST["data"] # type: ignore[assignment]
data = json.dumps(json.loads(data), indent=2)
except KeyError:
return HttpResponse(status=400, content="'data' is required.")
except Exception: # noqa
except Exception: # noqa: BLE001
return HttpResponse(status=400, content="'data' is is not valid json.")

response = HttpResponse(content_type="application/force-download")
Expand All @@ -65,7 +69,7 @@ def download_file(request: HttpRequest) -> HttpResponse: # pragma: no cover
# Added to site


def get_app_list(self: admin.AdminSite, request: HttpRequest, *args) -> List[AppDict]:
def get_app_list(self: admin.AdminSite, request: HttpRequest, *args: Any) -> List[AppDict]:
baseroute = admin_data_settings.NAME.lower().replace(" ", "-")
app_dict = self._build_app_dict(request, *args) or {} # pylint: disable=protected-access

Expand Down
8 changes: 5 additions & 3 deletions admin_data_views/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class AdminDataViewsSettings(NamedTuple):
#
# URLs for top-level categories. These will appear in the sidebar.
# URLs for item pages. These will not appear in the sidebar.
URLS: List[URLConfig] = []
URLS: List[URLConfig] = [] # noqa: RUF012
#
# Name of the admin data views section in admin panel
NAME: str = "Admin Data Views"
Expand All @@ -34,7 +34,8 @@ def perform_import(self, val: str, setting: str) -> Any:
for i, item in enumerate(val):
missing = {"route", "view", "name"}.difference(item.keys())
if missing:
raise RuntimeError(f"Missing keys in ADMIN_DATA_VIEWS[{i}]: {missing}")
msg = f"Missing keys in ADMIN_DATA_VIEWS[{i}]: {missing}"
raise RuntimeError(msg)

item["route"] = item["route"].rstrip("/").lstrip("/")
item["view"] = self.import_from_string(item["view"], setting)
Expand All @@ -45,7 +46,8 @@ def perform_import(self, val: str, setting: str) -> Any:

missing = {"route", "view", "name"}.difference(item["items"].keys())
if missing:
raise RuntimeError(f"Missing keys in ADMIN_DATA_VIEWS[{i}]['items']: {missing}")
msg = f"Missing keys in ADMIN_DATA_VIEWS[{i}]['items']: {missing}"
raise RuntimeError(msg)

item["items"]["route"] = item["items"]["route"].rstrip("/").lstrip("/")
item["items"]["view"] = self.import_from_string(item["items"]["view"], setting)
Expand Down
28 changes: 21 additions & 7 deletions admin_data_views/utils.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
from functools import wraps
from typing import TYPE_CHECKING

from django.contrib import admin
from django.http import HttpRequest
from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils.html import format_html

from .settings import admin_data_settings
from .typing import Any, Callable, ItemContext, ItemViewContext, TableContext, TableViewContext, URLConfig
from .typing import (
Any,
Callable,
ItemContext,
ItemViewContext,
TableContext,
TableViewContext,
URLConfig,
)

if TYPE_CHECKING:
from django.http import HttpRequest

__all__ = [
"render_with_item_view",
Expand Down Expand Up @@ -44,7 +55,7 @@ def wrapper(*args: Any, **kwargs: Any) -> TemplateResponse:
for header in context["table"]:
for row_no, cell in enumerate(context["table"][header]):
if item["items"] is not None and isinstance(cell, ItemLink):
cell = format_html(
cell = format_html( # noqa: PLW2901
'<a href="{}">{}</a>',
reverse(
viewname=f"admin:{item['items']['name']}",
Expand All @@ -61,7 +72,8 @@ def wrapper(*args: Any, **kwargs: Any) -> TemplateResponse:

break # Stop searching once view is found
else:
raise ValueError(f"Cannot find '{func_name}' in ADMIN_DATA_VIEWS setting.")
msg = f"Cannot find '{func_name}' in ADMIN_DATA_VIEWS setting."
raise ValueError(msg)

request: HttpRequest = args[0]
table_context.update(admin.site.each_context(request))
Expand Down Expand Up @@ -115,7 +127,8 @@ def wrapper(*args: Any, **kwargs: Any) -> TemplateResponse:
)
break # Stop searching once view is found
else:
raise ValueError(f"Cannot find '{func_name}' in ADMIN_DATA_VIEWS setting.")
msg = f"Cannot find '{func_name}' in ADMIN_DATA_VIEWS setting."
raise ValueError(msg)

request: HttpRequest = args[0]
item_context.update(admin.site.each_context(request))
Expand All @@ -127,8 +140,9 @@ def wrapper(*args: Any, **kwargs: Any) -> TemplateResponse:


class ItemLink:
def __init__(self, link_item: Any, /, **kwargs: Any):
"""Marks a link to an item for the given view.
def __init__(self, link_item: Any, /, **kwargs: Any) -> None:
"""
Marks a link to an item for the given view.
:param link_item: Link text.
:param args: Additional arguments to pass to the item route.
Expand Down
11 changes: 4 additions & 7 deletions manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,14 @@
import sys


def main():
def main() -> None:
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.django.settings")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.project.settings")
try:
from django.core.management import execute_from_command_line # pylint: disable=import-outside-toplevel
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
msg = "Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?"
raise ImportError(msg) from exc
execute_from_command_line(sys.argv)


Expand Down
Loading

0 comments on commit 43261ce

Please sign in to comment.