Skip to content

Commit

Permalink
return/apply black, isort
Browse files Browse the repository at this point in the history
  • Loading branch information
hnthh committed Nov 29, 2023
1 parent bec4e7d commit bb07cd4
Show file tree
Hide file tree
Showing 32 changed files with 66 additions and 187 deletions.
10 changes: 5 additions & 5 deletions {{cookiecutter.name}}/Makefile
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
manage = poetry run src/manage.py
numprocesses = 4

fmt:
poetry run autoflake --in-place --remove-all-unused-imports --recursive src tests
poetry run isort src tests
poetry run black src tests

checks:
$(manage) check
$(manage) makemigrations --check --dry-run --no-input
Expand All @@ -16,6 +11,11 @@ checks:
poetry run mypy src tests
poetry run dotenv-linter src/core/.env.ci

fmt:
poetry run autoflake --in-place --remove-all-unused-imports --recursive src tests
poetry run isort src tests
poetry run black src tests

test:
poetry run pytest --dead-fixtures
poetry run pytest --create-db --exitfirst --numprocesses ${numprocesses}
Expand Down
8 changes: 4 additions & 4 deletions {{cookiecutter.name}}/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ types-pillow = "^10.1.0.2"
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.black]
line_length = 160

[tool.flake8]
exclude = ["migrations", "__pycache__"]
ignore = [
Expand All @@ -82,13 +85,10 @@ inline-quotes = "\""
max-line-length = 160

[tool.isort]
extra_standard_library = ["pytest"]
include_trailing_comma = true
known_django = ["django", "restframework"]
line_length = 160
multi_line_output = 3
profile = "google"
sections = ["FUTURE", "STDLIB", "THIRDPARTY", "DJANGO", "FIRSTPARTY", "LOCALFOLDER"]
src_paths = ["src", "tests"]
use_parentheses = true

[tool.pytest.ini_options]
Expand Down
2 changes: 0 additions & 2 deletions {{cookiecutter.name}}/src/apps/a12n/api/serializers.py

This file was deleted.

3 changes: 1 addition & 2 deletions {{cookiecutter.name}}/src/apps/users/api/viewsets.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from django.db.models import QuerySet
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response

from django.db.models import QuerySet

from apps.users.api.serializers import UserSerializer
from apps.users.models import User

Expand Down
62 changes: 10 additions & 52 deletions {{cookiecutter.name}}/src/apps/users/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@

import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations
from django.db import models
import django.utils.timezone
from django.db import migrations, models


class Migration(migrations.Migration):
Expand All @@ -18,22 +17,9 @@ class Migration(migrations.Migration):
migrations.CreateModel(
name="User",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("password", models.CharField(max_length=128, verbose_name="password")),
(
"last_login",
models.DateTimeField(
blank=True, null=True, verbose_name="last login"
),
),
("last_login", models.DateTimeField(blank=True, null=True, verbose_name="last login")),
(
"is_superuser",
models.BooleanField(
Expand All @@ -45,43 +31,20 @@ class Migration(migrations.Migration):
(
"username",
models.CharField(
error_messages={
"unique": "A user with that username already exists."
},
error_messages={"unique": "A user with that username already exists."},
help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
max_length=150,
unique=True,
validators=[
django.contrib.auth.validators.UnicodeUsernameValidator()
],
validators=[django.contrib.auth.validators.UnicodeUsernameValidator()],
verbose_name="username",
),
),
(
"first_name",
models.CharField(
blank=True, max_length=150, verbose_name="first name"
),
),
(
"last_name",
models.CharField(
blank=True, max_length=150, verbose_name="last name"
),
),
(
"email",
models.EmailField(
blank=True, max_length=254, verbose_name="email address"
),
),
("first_name", models.CharField(blank=True, max_length=150, verbose_name="first name")),
("last_name", models.CharField(blank=True, max_length=150, verbose_name="last name")),
("email", models.EmailField(blank=True, max_length=254, verbose_name="email address")),
(
"is_staff",
models.BooleanField(
default=False,
help_text="Designates whether the user can log into this admin site.",
verbose_name="staff status",
),
models.BooleanField(default=False, help_text="Designates whether the user can log into this admin site.", verbose_name="staff status"),
),
(
"is_active",
Expand All @@ -91,12 +54,7 @@ class Migration(migrations.Migration):
verbose_name="active",
),
),
(
"date_joined",
models.DateTimeField(
default=django.utils.timezone.now, verbose_name="date joined"
),
),
("date_joined", models.DateTimeField(default=django.utils.timezone.now, verbose_name="date joined")),
(
"groups",
models.ManyToManyField(
Expand Down
4 changes: 2 additions & 2 deletions {{cookiecutter.name}}/src/core/.env.ci
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
DEBUG=Off
SECRET_KEY=l!@xGb!Jkd]pQsvtU,@y`=%/c}mY;]oYwnsVeU}".VwwClOX
DATABASE_URL=sqlite:///db.sqlite
DEBUG=off
SECRET_KEY=l!@xGb!Jkd]pQsvtU,@y`=%/c}mY;]oYwnsVeU}".VwwClOX
3 changes: 1 addition & 2 deletions {{cookiecutter.name}}/src/core/api/pagination.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from rest_framework.pagination import PageNumberPagination

from django.conf import settings
from rest_framework.pagination import PageNumberPagination


class AppPagination(PageNumberPagination):
Expand Down
4 changes: 1 addition & 3 deletions {{cookiecutter.name}}/src/core/api/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,4 @@

class AppJSONRenderer(CamelCaseJSONRenderer):
charset = "utf-8" # force DRF to add charset header to the content-type
json_underscoreize = {
"no_underscore_before_number": True
} # https://github.com/vbabiy/djangorestframework-camel-case#underscoreize-options
json_underscoreize = {"no_underscore_before_number": True} # https://github.com/vbabiy/djangorestframework-camel-case#underscoreize-options
3 changes: 1 addition & 2 deletions {{cookiecutter.name}}/src/core/api/throttling.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from typing import Protocol

from django.conf import settings
from rest_framework.request import Request
from rest_framework.views import APIView

from django.conf import settings


class BaseThrottle(Protocol):
def allow_request(self, request: Request, view: APIView) -> bool:
Expand Down
22 changes: 6 additions & 16 deletions {{cookiecutter.name}}/src/core/api/viewsets.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
from typing import Any, Optional, Protocol, Type

from rest_framework import mixins
from rest_framework import status
from rest_framework.mixins import CreateModelMixin
from rest_framework.mixins import UpdateModelMixin
from rest_framework import mixins, status
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
Expand Down Expand Up @@ -38,14 +36,10 @@ def get_object(self, *args: Any, **kwargs: Any) -> Any:
class DefaultCreateModelMixin(CreateModelMixin):
"""Return detail-serialized created instance"""

def create(
self: BaseGenericViewSet, request: Request, *args: Any, **kwargs: Any
) -> Response:
def create(self: BaseGenericViewSet, request: Request, *args: Any, **kwargs: Any) -> Response:
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
instance = self.perform_create(
serializer
) # No getting created instance in original DRF
instance = self.perform_create(serializer) # No getting created instance in original DRF
headers = self.get_success_headers(serializer.data)
return self.get_response(instance, status.HTTP_201_CREATED, headers)

Expand All @@ -56,16 +50,12 @@ def perform_create(self: BaseGenericViewSet, serializer: Any) -> Any:
class DefaultUpdateModelMixin(UpdateModelMixin):
"""Return detail-serialized updated instance"""

def update(
self: BaseGenericViewSet, request: Request, *args: Any, **kwargs: Any
) -> Response:
def update(self: BaseGenericViewSet, request: Request, *args: Any, **kwargs: Any) -> Response:
partial = kwargs.pop("partial", False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
instance = self.perform_update(
serializer
) # No getting updated instance in original DRF
instance = self.perform_update(serializer) # No getting updated instance in original DRF

if getattr(instance, "_prefetched_objects_cache", None):
# If 'prefetch_related' has been applied to a queryset, we need to
Expand Down
9 changes: 0 additions & 9 deletions {{cookiecutter.name}}/src/core/asgi.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
"""
ASGI config for app project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application
Expand Down
12 changes: 3 additions & 9 deletions {{cookiecutter.name}}/src/core/conf/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@

REST_FRAMEWORK = {
"DEFAULT_FILTER_BACKENDS": ("django_filters.rest_framework.DjangoFilterBackend",),
"DEFAULT_PERMISSION_CLASSES": (
"rest_framework.permissions.IsAuthenticatedOrReadOnly",
),
"DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticatedOrReadOnly",),
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
"rest_framework_jwt.authentication.JSONWebTokenAuthentication",
Expand All @@ -34,12 +32,8 @@

# Adding session auth and browsable API at the developer machine
if env("DEBUG", cast=bool, default=False):
REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"].append(
"rest_framework.authentication.SessionAuthentication"
)
REST_FRAMEWORK["DEFAULT_RENDERER_CLASSES"].append(
"djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer"
)
REST_FRAMEWORK["DEFAULT_AUTHENTICATION_CLASSES"].append("rest_framework.authentication.SessionAuthentication")
REST_FRAMEWORK["DEFAULT_RENDERER_CLASSES"].append("djangorestframework_camel_case.render.CamelCaseBrowsableAPIRenderer")


# Set up drf_spectacular, https://drf-spectacular.readthedocs.io/en/latest/settings.html
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@ class Command(BaseCommand):
"""Disable automatic names for django migrations, thanks https://adamj.eu/tech/2020/02/24/how-to-disallow-auto-named-django-migrations/"""

def handle(self, *app_labels, **options):
if options["name"] is None and not any(
[options["dry_run"], options["check_changes"]]
):
raise MakemigrationsError(
"Migration name is required. Run again with `-n/--name` argument and specify name explicitly."
)
if options["name"] is None and not any([options["dry_run"], options["check_changes"]]):
raise MakemigrationsError("Migration name is required. Run again with `-n/--name` argument and specify name explicitly.")

super().handle(*app_labels, **options)
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,11 @@ class Command(BaseCommand):

def handle(self, **options):
if "template" not in options or options["template"] is None:
options["template"] = str(
Path(settings.BASE_DIR).parent / ".django-app-template"
)
options["template"] = str(Path(settings.BASE_DIR).parent / ".django-app-template")

super().handle(**options)

testsdir = (
Path(settings.BASE_DIR).parent.parent / "tests" / "apps" / options["name"]
)
testsdir = Path(settings.BASE_DIR).parent.parent / "tests" / "apps" / options["name"]
testsdir.mkdir(parents=True, exist_ok=True)

(testsdir / "__init__.py").touch()
Expand Down
4 changes: 1 addition & 3 deletions {{cookiecutter.name}}/src/core/middleware/real_ip.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
from typing import Callable

from django.http import HttpRequest, HttpResponse
from ipware import get_client_ip

from django.http import HttpRequest
from django.http import HttpResponse


def real_ip_middleware(get_response: Callable) -> Callable:
"""Set request.META["REMOTE_ADDR"] to ip guessed by django-ipware.
Expand Down
1 change: 0 additions & 1 deletion {{cookiecutter.name}}/src/core/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from typing import Any

from behaviors.behaviors import Timestamped # type: ignore

from django.contrib.contenttypes.models import ContentType
from django.db import models

Expand Down
3 changes: 1 addition & 2 deletions {{cookiecutter.name}}/src/core/services.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from abc import ABCMeta
from abc import abstractmethod
from abc import ABCMeta, abstractmethod
from typing import Any, Callable


Expand Down
3 changes: 1 addition & 2 deletions {{cookiecutter.name}}/src/core/testing/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from core.testing.api import ApiClient
from core.testing.factory import FixtureFactory
from core.testing.factory import register
from core.testing.factory import FixtureFactory, register

__all__ = [
"ApiClient",
Expand Down
4 changes: 1 addition & 3 deletions {{cookiecutter.name}}/src/core/testing/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ def __init__(self, factory: "FixtureFactory", count: int) -> None:
self.count = count

def __getattr__(self, name: str) -> Callable:
return lambda *args, **kwargs: [
getattr(self.factory, name)(*args, **kwargs) for _ in range(self.count)
]
return lambda *args, **kwargs: [getattr(self.factory, name)(*args, **kwargs) for _ in range(self.count)]


class FixtureFactory:
Expand Down
3 changes: 1 addition & 2 deletions {{cookiecutter.name}}/src/core/urls/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.contrib import admin
from django.urls import include
from django.urls import path
from django.urls import include, path

api = [
path("v1/", include("core.urls.v1", namespace="v1")),
Expand Down
7 changes: 2 additions & 5 deletions {{cookiecutter.name}}/src/core/urls/v1.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
from drf_spectacular.views import SpectacularAPIView
from drf_spectacular.views import SpectacularSwaggerView

from django.urls import include
from django.urls import path
from django.urls import include, path
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView

app_name = "api_v1"

Expand Down
9 changes: 0 additions & 9 deletions {{cookiecutter.name}}/src/core/wsgi.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
"""
WSGI config for app project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
Expand Down
Loading

0 comments on commit bb07cd4

Please sign in to comment.