Skip to content

Commit

Permalink
init refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
ALittleMoron committed Sep 5, 2024
1 parent 08db9c6 commit 764c398
Show file tree
Hide file tree
Showing 25 changed files with 579 additions and 611 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ __pycache__
.ruff_cache
project.todo
.pdm-python
dist
dist
.zed
423 changes: 176 additions & 247 deletions pdm.lock

Large diffs are not rendered by default.

49 changes: 12 additions & 37 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,37 +1,5 @@
[tool.ruff]
lint.select = [
"A",
"B",
"D",
"E",
"F",
"G",
"N",
"Q",
"S",
"C90",
"UP",
"ANN",
"PLR",
"ASYNC",
"FBT",
"COM",
"COM",
"DTZ",
"DJ",
"EM",
"ICN",
"PIE",
"T20",
"PYI",
"PT",
"SIM",
"TCH",
"INT",
"PTH",
"ERA",
"TRY",
]
lint.select = ["ALL"]
line-length = 100
output-format = "full"
exclude = [
Expand All @@ -56,6 +24,8 @@ lint.ignore = [
"ANN101",
"ANN102",
"PLR0913",
"UP037",
"PLC0414",
]

[tool.ruff.lint.pydocstyle]
Expand Down Expand Up @@ -135,7 +105,7 @@ distribution = true

[tool.pdm.dev-dependencies]
dev = [
"ruff>=0.3.4",
"ruff>=0.5.5",
"vulture>=2.11",
"pytest>=8.1.1",
"black>=24.3.0",
Expand All @@ -156,6 +126,9 @@ dev = [
"ipython>=8.19.0",
]

[tool.pyright]
venvPath = "."
venv = ".venv"

[project]
name = "sqlrepo"
Expand All @@ -166,12 +139,14 @@ requires-python = ">=3.11"
readme = "README.md"
license = { text = "MIT" }
dependencies = [
"sqlalchemy>=2.0.29",
"python-dev-utils[sqlalchemy_filters]>=2.3.0",
"sqlalchemy>=2.0",
"python-dev-utils>=7.0.1",
"sqlalchemy-dev-utils>=1.0.1",
"sqlalchemy-filter-converter>=1.3.0",
]

[project.optional-dependencies]
fastapi = ["fastapi>=0.100"]
fastapi = ["fastapi>=0.100", "verbose_http_exceptions>=1.1.1"]

[build-system]
requires = ["pdm-backend"]
Expand Down
6 changes: 3 additions & 3 deletions sqlrepo/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Final, Literal, TypeAlias

from dev_utils.sqlalchemy.filters.converters import (
from sqlalchemy_filter_converter import (
AdvancedOperatorFilterConverter,
BaseFilterConverter,
DjangoLikeFilterConverter,
SimpleFilterConverter,
)
from dev_utils.sqlalchemy.filters.types import FilterConverterStrategiesLiteral
from sqlalchemy_filter_converter.types import FilterConverterStrategiesLiteral

StrField: TypeAlias = str

Expand All @@ -29,7 +29,7 @@
class RepositoryConfig:
"""Repository config as dataclass."""

# TODO: add specific_column_mapping to filters, joins and loads.
# TODO: add specific_column_mapping to filters, joins and loads. # noqa: FIX002, TD002, TD003
specific_column_mapping: "dict[str, InstrumentedAttribute[Any]]" = field(default_factory=dict)
"""
Warning! Current version of sqlrepo doesn't support this mapping for filters, joins and loads.
Expand Down
2 changes: 1 addition & 1 deletion sqlrepo/ext/fastapi/containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from fastapi import Depends, Request

from sqlrepo.ext.fastapi.stubs import _get_session_stub # type: ignore
from sqlrepo.ext.fastapi.stubs import _get_session_stub # type: ignore[reportPrivateUsage]

if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncSession
Expand Down
2 changes: 1 addition & 1 deletion sqlrepo/ext/fastapi/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class AbstractBasePagination:
current_page: int

def __init__(self) -> None: # pragma: no coverage
raise NotImplementedError()
raise NotImplementedError


class LimitOffsetPagination(AbstractBasePagination):
Expand Down
39 changes: 17 additions & 22 deletions sqlrepo/ext/fastapi/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@
from inspect import isclass
from typing import TYPE_CHECKING, Any, ForwardRef, Generic, TypeVar, get_args

from dev_utils.verbose_http_exceptions import BaseVerboseHTTPException
from fastapi import Depends, HTTPException, Request, status
from pydantic import BaseModel, TypeAdapter
from sqlalchemy.orm.decl_api import DeclarativeBase
from verbose_http_exceptions import BaseVerboseHTTPException

from sqlrepo.ext.fastapi.helpers import NotSet, NotSetType
from sqlrepo.ext.fastapi.pagination import PaginatedResult, PaginationMeta
from sqlrepo.ext.fastapi.stubs import _get_session_stub # type: ignore
from sqlrepo.logging import logger
from sqlrepo.ext.fastapi.stubs import _get_session_stub # type: ignore[reportPrivateUsage]

if TYPE_CHECKING:
from collections.abc import Sequence
Expand Down Expand Up @@ -44,22 +43,22 @@ def resolve_type(
value.__forward_arg__,
detail_schema_globals,
)
except Exception as exc:
except (ImportError, TypeError, AttributeError, NameError) as exc:
msg = (
"Can't evaluate ForwardRef of generic type. "
"Don't use type in generic with quotes. "
f"Original exception: {str(exc)}"
f"Original exception: {exc!s}"
)
warnings.warn(msg, ServiceClassIncorrectUseWarning, stacklevel=2)
return
return None
elif isinstance(value, TypeVar):
msg = "GenericType was not passed for pydantic BaseModel subclass."
warnings.warn(msg, ServiceClassIncorrectUseWarning, stacklevel=2)
return
return None
elif not issubclass(value, BaseModel):
msg = "Passed GenericType is not pydantic BaseModel subclass."
warnings.warn(msg, ServiceClassIncorrectUseWarning, stacklevel=2)
return
return None
return value


Expand All @@ -75,42 +74,38 @@ class BaseService(Generic[TModel, TDetailSchema, VListSchema]):
def __init_subclass__(cls) -> None: # noqa: D105
super().__init_subclass__()
if not isinstance(
cls.detail_schema, # type: ignore
cls.detail_schema,
NotSetType,
) and not isinstance(
cls.list_schema, # type: ignore
cls.list_schema,
NotSetType,
):
msg = "All needed attributes are set and nothing to do."
logger.debug(msg)
return
if cls.__inheritance_check_model_class__ is False:
cls.__inheritance_check_model_class__ = True
msg = f"Skip all generic type checking in {cls.__name__}."
logger.debug(msg)
return
try:
# PEP-560: https://peps.python.org/pep-0560/
# NOTE: this code is needed for getting type from generic: Generic[int] -> int type
# get_args get params from __orig_bases__, that contains Generic passed types.
_, detail_schema_type, list_schema_type, *_ = get_args(cls.__orig_bases__[0]) # type: ignore
except Exception as exc: # pragma: no coverage
_, detail_schema_type, list_schema_type, *_ = get_args(cls.__orig_bases__[0]) # type: ignore[reportAttributeAccessIssue]
except (AttributeError, IndexError, TypeError) as exc:
msg = (
f"Error during getting information about Generic types for {cls.__name__}. "
f"Original exception: {str(exc)}"
f"Original exception: {exc!s}"
)
warnings.warn(msg, ServiceClassIncorrectUseWarning, stacklevel=2)
return
if (
isinstance(getattr(cls, "detail_schema", NotSet), NotSetType)
and (detail_schema_type := resolve_type(cls, detail_schema_type)) is not None
):
cls.detail_schema = detail_schema_type # type: ignore
cls.detail_schema = detail_schema_type
if (
isinstance(getattr(cls, "list_schema", NotSet), NotSetType)
and (list_schema_type := resolve_type(cls, list_schema_type)) is not None
):
cls.list_schema = list_schema_type # type: ignore
cls.list_schema = list_schema_type

detail_schema: "type[TDetailSchema] | NotSetType" = NotSet
list_schema: "type[VListSchema]| NotSetType" = NotSet
Expand Down Expand Up @@ -139,7 +134,7 @@ def _resolve_entity_not_found(self) -> None:
)
raise self.not_found_exception(message)

def resolve_entity(self, entity: "TModel | None") -> "TDetailSchema": # noqa: ANN401
def resolve_entity(self, entity: "TModel | None") -> "TDetailSchema":
"""Resolve given SQLAlchemy entity and return pydantic schema."""
if entity is None:
self._resolve_entity_not_found()
Expand Down Expand Up @@ -177,7 +172,7 @@ def init_repositories(self, session: "AsyncSession") -> None:
Define your own method for it and specify your own methods for working with repositories.
"""
raise NotImplementedError()
raise NotImplementedError

def __init__(
self,
Expand All @@ -199,7 +194,7 @@ def init_repositories(self, session: "Session") -> None:
Define your own method for it and specify your own methods for working with repositories.
"""
raise NotImplementedError()
raise NotImplementedError

def __init__(
self,
Expand Down
33 changes: 0 additions & 33 deletions sqlrepo/logging.py

This file was deleted.

Loading

0 comments on commit 764c398

Please sign in to comment.