liniting, black, mypy fixes

This commit is contained in:
collerek
2020-10-31 18:22:15 +01:00
parent 7d5e291a19
commit 3c10892db7
16 changed files with 157 additions and 155 deletions

View File

@ -1,4 +1,4 @@
from typing import Any, List, Optional, TYPE_CHECKING, Type, Union, Sequence
from typing import Any, List, Optional, Sequence, TYPE_CHECKING, Type, Union
from ormar.fields import BaseField
from ormar.fields.foreign_key import ForeignKeyField
@ -10,13 +10,13 @@ REF_PREFIX = "#/components/schemas/"
def ManyToMany(
to: Type["Model"],
through: Type["Model"],
*,
name: str = None,
unique: bool = False,
virtual: bool = False,
**kwargs: Any
to: Type["Model"],
through: Type["Model"],
*,
name: str = None,
unique: bool = False,
virtual: bool = False,
**kwargs: Any
) -> Type["ManyToManyField"]:
to_field = to.Meta.model_fields[to.Meta.pkname]
related_name = kwargs.pop("related_name", None)
@ -50,7 +50,8 @@ def ManyToMany(
class ManyToManyField(ForeignKeyField):
through: Type["Model"]
if TYPE_CHECKING: # pragma nocover
if TYPE_CHECKING: # noqa: C901; pragma nocover
@staticmethod
async def add(item: "Model") -> None:
pass
@ -62,7 +63,7 @@ class ManyToManyField(ForeignKeyField):
from ormar import QuerySet
@staticmethod
def filter(**kwargs: Any) -> "QuerySet": # noqa: A003
def filter(**kwargs: Any) -> "QuerySet": # noqa: A003, A001
pass
@staticmethod
@ -70,15 +71,15 @@ class ManyToManyField(ForeignKeyField):
pass
@staticmethod
async def exists(self) -> bool:
return await self.queryset.exists()
async def exists() -> bool:
pass
@staticmethod
async def count(self) -> int:
return await self.queryset.count()
async def count() -> int:
pass
@staticmethod
async def clear(self) -> int:
async def clear() -> int:
pass
@staticmethod
@ -86,21 +87,21 @@ class ManyToManyField(ForeignKeyField):
pass
@staticmethod
def offset(self, offset: int) -> "QuerySet":
def offset(offset: int) -> "QuerySet":
pass
@staticmethod
async def first(self, **kwargs: Any) -> "Model":
async def first(**kwargs: Any) -> "Model":
pass
@staticmethod
async def get(self, **kwargs: Any) -> "Model":
async def get(**kwargs: Any) -> "Model":
pass
@staticmethod
async def all(self, **kwargs: Any) -> Sequence[Optional["Model"]]: # noqa: A003
async def all(**kwargs: Any) -> Sequence[Optional["Model"]]: # noqa: A003, A001
pass
@staticmethod
async def create(self, **kwargs: Any) -> "Model":
async def create(**kwargs: Any) -> "Model":
pass

View File

@ -12,7 +12,7 @@ from ormar.fields.base import BaseField # noqa I101
def is_field_nullable(
nullable: Optional[bool], default: Any, server_default: Any
nullable: Optional[bool], default: Any, server_default: Any
) -> bool:
if nullable is None:
return default is not None or server_default is not None
@ -63,15 +63,15 @@ class String(ModelFieldFactory, str):
_pydantic_type = pydantic.ConstrainedStr
def __new__( # type: ignore # noqa CFQ002
cls,
*,
allow_blank: bool = True,
strip_whitespace: bool = False,
min_length: int = None,
max_length: int = None,
curtail_length: int = None,
regex: str = None,
**kwargs: Any
cls,
*,
allow_blank: bool = True,
strip_whitespace: bool = False,
min_length: int = None,
max_length: int = None,
curtail_length: int = None,
regex: str = None,
**kwargs: Any
) -> Type[BaseField]: # type: ignore
kwargs = {
**kwargs,
@ -102,12 +102,12 @@ class Integer(ModelFieldFactory, int):
_pydantic_type = pydantic.ConstrainedInt
def __new__( # type: ignore
cls,
*,
minimum: int = None,
maximum: int = None,
multiple_of: int = None,
**kwargs: Any
cls,
*,
minimum: int = None,
maximum: int = None,
multiple_of: int = None,
**kwargs: Any
) -> Type[BaseField]:
autoincrement = kwargs.pop("autoincrement", None)
autoincrement = (
@ -137,7 +137,7 @@ class Text(ModelFieldFactory, str):
_pydantic_type = pydantic.ConstrainedStr
def __new__( # type: ignore
cls, *, allow_blank: bool = True, strip_whitespace: bool = False, **kwargs: Any
cls, *, allow_blank: bool = True, strip_whitespace: bool = False, **kwargs: Any
) -> Type[BaseField]:
kwargs = {
**kwargs,
@ -160,12 +160,12 @@ class Float(ModelFieldFactory, float):
_pydantic_type = pydantic.ConstrainedFloat
def __new__( # type: ignore
cls,
*,
minimum: float = None,
maximum: float = None,
multiple_of: int = None,
**kwargs: Any
cls,
*,
minimum: float = None,
maximum: float = None,
multiple_of: int = None,
**kwargs: Any
) -> Type[BaseField]:
kwargs = {
**kwargs,
@ -234,12 +234,12 @@ class BigInteger(Integer, int):
_pydantic_type = pydantic.ConstrainedInt
def __new__( # type: ignore
cls,
*,
minimum: int = None,
maximum: int = None,
multiple_of: int = None,
**kwargs: Any
cls,
*,
minimum: int = None,
maximum: int = None,
multiple_of: int = None,
**kwargs: Any
) -> Type[BaseField]:
autoincrement = kwargs.pop("autoincrement", None)
autoincrement = (
@ -269,16 +269,16 @@ class Decimal(ModelFieldFactory, decimal.Decimal):
_pydantic_type = pydantic.ConstrainedDecimal
def __new__( # type: ignore # noqa CFQ002
cls,
*,
minimum: float = None,
maximum: float = None,
multiple_of: int = None,
precision: int = None,
scale: int = None,
max_digits: int = None,
decimal_places: int = None,
**kwargs: Any
cls,
*,
minimum: float = None,
maximum: float = None,
multiple_of: int = None,
precision: int = None,
scale: int = None,
max_digits: int = None,
decimal_places: int = None,
**kwargs: Any
) -> Type[BaseField]:
kwargs = {
**kwargs,

View File

@ -42,7 +42,7 @@ def register_relation_on_build(table_name: str, field: Type[ForeignKeyField]) ->
def register_many_to_many_relation_on_build(
table_name: str, field: Type[ManyToManyField]
table_name: str, field: Type[ManyToManyField]
) -> None:
alias_manager.add_relation_type(field.through.Meta.tablename, table_name)
alias_manager.add_relation_type(
@ -51,11 +51,11 @@ def register_many_to_many_relation_on_build(
def reverse_field_not_already_registered(
child: Type["Model"], child_model_name: str, parent_model: Type["Model"]
child: Type["Model"], child_model_name: str, parent_model: Type["Model"]
) -> bool:
return (
child_model_name not in parent_model.__fields__
and child.get_name() not in parent_model.__fields__
child_model_name not in parent_model.__fields__
and child.get_name() not in parent_model.__fields__
)
@ -66,7 +66,7 @@ def expand_reverse_relationships(model: Type["Model"]) -> None:
parent_model = model_field.to
child = model
if reverse_field_not_already_registered(
child, child_model_name, parent_model
child, child_model_name, parent_model
):
register_reverse_model_fields(
parent_model, child, child_model_name, model_field
@ -74,10 +74,10 @@ def expand_reverse_relationships(model: Type["Model"]) -> None:
def register_reverse_model_fields(
model: Type["Model"],
child: Type["Model"],
child_model_name: str,
model_field: Type["ForeignKeyField"],
model: Type["Model"],
child: Type["Model"],
child_model_name: str,
model_field: Type["ForeignKeyField"],
) -> None:
if issubclass(model_field, ManyToManyField):
model.Meta.model_fields[child_model_name] = ManyToMany(
@ -92,7 +92,7 @@ def register_reverse_model_fields(
def adjust_through_many_to_many_model(
model: Type["Model"], child: Type["Model"], model_field: Type[ManyToManyField]
model: Type["Model"], child: Type["Model"], model_field: Type[ManyToManyField]
) -> None:
model_field.through.Meta.model_fields[model.get_name()] = ForeignKey(
model, name=model.get_name(), ondelete="CASCADE"
@ -109,7 +109,7 @@ def adjust_through_many_to_many_model(
def create_pydantic_field(
field_name: str, model: Type["Model"], model_field: Type[ManyToManyField]
field_name: str, model: Type["Model"], model_field: Type[ManyToManyField]
) -> None:
model_field.through.__fields__[field_name] = ModelField(
name=field_name,
@ -121,7 +121,7 @@ def create_pydantic_field(
def create_and_append_m2m_fk(
model: Type["Model"], model_field: Type[ManyToManyField]
model: Type["Model"], model_field: Type[ManyToManyField]
) -> None:
column = sqlalchemy.Column(
model.get_name(),
@ -137,7 +137,7 @@ def create_and_append_m2m_fk(
def check_pk_column_validity(
field_name: str, field: BaseField, pkname: Optional[str]
field_name: str, field: BaseField, pkname: Optional[str]
) -> Optional[str]:
if pkname is not None:
raise ModelDefinitionError("Only one primary key column is allowed.")
@ -147,7 +147,7 @@ def check_pk_column_validity(
def sqlalchemy_columns_from_model_fields(
model_fields: Dict, table_name: str
model_fields: Dict, table_name: str
) -> Tuple[Optional[str], List[sqlalchemy.Column]]:
columns = []
pkname = None
@ -161,9 +161,9 @@ def sqlalchemy_columns_from_model_fields(
if field.primary_key:
pkname = check_pk_column_validity(field_name, field, pkname)
if (
not field.pydantic_only
and not field.virtual
and not issubclass(field, ManyToManyField)
not field.pydantic_only
and not field.virtual
and not issubclass(field, ManyToManyField)
):
columns.append(field.get_column(field_name))
register_relation_in_alias_manager(table_name, field)
@ -171,7 +171,7 @@ def sqlalchemy_columns_from_model_fields(
def register_relation_in_alias_manager(
table_name: str, field: Type[ForeignKeyField]
table_name: str, field: Type[ForeignKeyField]
) -> None:
if issubclass(field, ManyToManyField):
register_many_to_many_relation_on_build(table_name, field)
@ -180,7 +180,7 @@ def register_relation_in_alias_manager(
def populate_default_pydantic_field_value(
ormar_field: Type[BaseField], field_name: str, attrs: dict
ormar_field: Type[BaseField], field_name: str, attrs: dict
) -> dict:
curr_def_value = attrs.get(field_name, ormar.Undefined)
if lenient_issubclass(curr_def_value, ormar.fields.BaseField):
@ -193,7 +193,7 @@ def populate_default_pydantic_field_value(
def check_if_field_annotation_or_value_is_ormar(
field: Any, field_name: str, attrs: Dict
field: Any, field_name: str, attrs: Dict
) -> bool:
return lenient_issubclass(field, BaseField) or issubclass(
attrs.get(field_name, type), BaseField
@ -201,15 +201,21 @@ def check_if_field_annotation_or_value_is_ormar(
def extract_field_from_annotation_or_value(
field: Any, field_name: str, attrs: Dict
field: Any, field_name: str, attrs: Dict
) -> Type[ormar.fields.BaseField]:
return field if lenient_issubclass(field, BaseField) else attrs.get(field_name)
def populate_pydantic_default_values(attrs: Dict) -> Tuple[Dict, Dict]:
model_fields = {}
potential_fields = {k: v for k, v in attrs["__annotations__"].items() if lenient_issubclass(v, BaseField)}
potential_fields.update({k: v for k, v in attrs.items() if lenient_issubclass(v, BaseField)})
potential_fields = {
k: v
for k, v in attrs["__annotations__"].items()
if lenient_issubclass(v, BaseField)
}
potential_fields.update(
{k: v for k, v in attrs.items() if lenient_issubclass(v, BaseField)}
)
for field_name, field in potential_fields.items():
# ormar fields can be used as annotation or as default value
if check_if_field_annotation_or_value_is_ormar(field, field_name, attrs):
@ -226,17 +232,15 @@ def populate_pydantic_default_values(attrs: Dict) -> Tuple[Dict, Dict]:
return attrs, model_fields
def extract_annotations_and_default_vals(
attrs: dict
) -> Tuple[Dict, Dict]:
key = '__annotations__'
def extract_annotations_and_default_vals(attrs: dict) -> Tuple[Dict, Dict]:
key = "__annotations__"
attrs[key] = attrs.get(key, {})
attrs, model_fields = populate_pydantic_default_values(attrs)
return attrs, model_fields
def populate_meta_tablename_columns_and_pk(
name: str, new_model: Type["Model"]
name: str, new_model: Type["Model"]
) -> Type["Model"]:
tablename = name.lower() + "s"
new_model.Meta.tablename = (
@ -262,7 +266,7 @@ def populate_meta_tablename_columns_and_pk(
def populate_meta_sqlalchemy_table_if_required(
new_model: Type["Model"],
new_model: Type["Model"],
) -> Type["Model"]:
if not hasattr(new_model.Meta, "table"):
new_model.Meta.table = sqlalchemy.Table(
@ -304,7 +308,7 @@ def choices_validator(cls: Type["Model"], values: Dict[str, Any]) -> Dict[str, A
def populate_choices_validators( # noqa CCR001
model: Type["Model"], attrs: Dict
model: Type["Model"], attrs: Dict
) -> None:
if model_initialized_and_has_model_fields(model):
for _, field in model.Meta.model_fields.items():
@ -317,7 +321,7 @@ def populate_choices_validators( # noqa CCR001
class ModelMetaclass(pydantic.main.ModelMetaclass):
def __new__( # type: ignore
mcs: "ModelMetaclass", name: str, bases: Any, attrs: dict
mcs: "ModelMetaclass", name: str, bases: Any, attrs: dict
) -> "ModelMetaclass":
attrs["Config"] = get_pydantic_base_orm_config()
attrs["__name__"] = name

View File

@ -45,12 +45,12 @@ class Model(NewBaseModel):
@classmethod
def from_row( # noqa CCR001
cls: Type[T],
row: sqlalchemy.engine.ResultProxy,
select_related: List = None,
related_models: Any = None,
previous_table: str = None,
fields: List = None,
cls: Type[T],
row: sqlalchemy.engine.ResultProxy,
select_related: List = None,
related_models: Any = None,
previous_table: str = None,
fields: List = None,
) -> Optional[T]:
item: Dict[str, Any] = {}
@ -60,9 +60,9 @@ class Model(NewBaseModel):
related_models = group_related_list(select_related)
if (
previous_table
and previous_table in cls.Meta.model_fields
and issubclass(cls.Meta.model_fields[previous_table], ManyToManyField)
previous_table
and previous_table in cls.Meta.model_fields
and issubclass(cls.Meta.model_fields[previous_table], ManyToManyField)
):
previous_table = cls.Meta.model_fields[
previous_table
@ -90,12 +90,12 @@ class Model(NewBaseModel):
@classmethod
def populate_nested_models_from_row(
cls,
item: dict,
row: sqlalchemy.engine.ResultProxy,
related_models: Any,
previous_table: sqlalchemy.Table,
fields: List = None,
cls,
item: dict,
row: sqlalchemy.engine.ResultProxy,
related_models: Any,
previous_table: sqlalchemy.Table,
fields: List = None,
) -> dict:
for related in related_models:
if isinstance(related_models, dict) and related_models[related]:
@ -119,12 +119,12 @@ class Model(NewBaseModel):
@classmethod
def extract_prefixed_table_columns( # noqa CCR001
cls,
item: dict,
row: sqlalchemy.engine.result.ResultProxy,
table_prefix: str,
fields: List = None,
nested: bool = False,
cls,
item: dict,
row: sqlalchemy.engine.result.ResultProxy,
table_prefix: str,
fields: List = None,
nested: bool = False,
) -> dict:
# databases does not keep aliases in Record for postgres, change to raw row