Skip to content

Commit

Permalink
Merge pull request #13 from devind-team/12-перенос-типов-на-strawberry
Browse files Browse the repository at this point in the history
12 перенос типов на strawberry
  • Loading branch information
surguh committed Jul 8, 2022
2 parents 39d21f7 + 1c63033 commit fbfe36a
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 107 deletions.
4 changes: 2 additions & 2 deletions devind_helpers/orm_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
from typing import Type, Union, Optional, Protocol

from django.db.models import Model, Manager, QuerySet
from django.core.exceptions import ObjectDoesNotExist

from devind_helpers.exceptions import NotFound

__all__ = ('get_object_or_404', 'get_object_or_none',)

Expand All @@ -27,7 +27,7 @@ def get_object_or_404(klass: Union[Type[Model], Manager, QuerySet], *args, **kwa
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
raise NotFound()
raise ObjectDoesNotExist(f'Объект {klass.__name__} не найден')


def get_object_or_none(klass: Union[Type[Model], Manager, QuerySet], *args, **kwargs) -> Optional[Model]:
Expand Down
2 changes: 1 addition & 1 deletion devind_helpers/schema/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .mutations import BaseMutation

29 changes: 0 additions & 29 deletions devind_helpers/schema/connections.py

This file was deleted.

30 changes: 0 additions & 30 deletions devind_helpers/schema/mutations.py

This file was deleted.

76 changes: 32 additions & 44 deletions devind_helpers/schema/types.py
Original file line number Diff line number Diff line change
@@ -1,59 +1,44 @@
from typing import Dict, List
import enum
from strawberry_django_plus import gql

import graphene
from flatten_dict import flatten
from graphene import ObjectType

from devind_helpers.import_from_file import ImportFromFile


class ErrorFieldType(ObjectType):
"""Ошибка в поле формы"""

field = graphene.String(required=True, description='Поле формы')
messages = graphene.List(graphene.NonNull(graphene.String), required=True, description='Ошибки')

@classmethod
def from_validator(cls, messages: Dict[str, Dict[str, str]]) -> List['ErrorFieldType']:
"""Получение ошибок из валидатора."""

return [cls(field=field, messages=msg.values()) for field, msg in messages.items()]

@classmethod
def from_messages_dict(cls, message_dict: Dict[str, List[str]]) -> List['ErrorFieldType']:
"""Получение ошибок из словаря сообщений ValidationError."""

return [cls(field=field, messages=values) for field, values in message_dict.items()]
from devind_helpers.import_from_file import ImportFromFile


class RowFieldErrorType(ObjectType):
@gql.type
class RowFieldErrorType:
"""Ошибка в строке."""

row = graphene.Int(required=True, description='Номер строки с ошибкой')
errors = graphene.List(ErrorFieldType, required=True, description='Ошибки, возникающие в строке')
row: int = gql.field(description='Номер строки с ошибкой')
errors: list[gql.OperationMessage] = gql.field(description='Ошибки, возникающие в строке')


class TableCellType(ObjectType):
@gql.type
class TableCellType:
"""Ячейка документа."""

header = graphene.String(required=True, description='Заголовок ячейки')
value = graphene.String(default_value='-', description='Значение ячейки')
align = graphene.String(default_value='left', description='Выравнивание')
type = graphene.String(default_value='string', description='Тип ячейки')
header: str = gql.field(description='Заголовок ячейки')
value: str = gql.field(default='-', description='Значение ячейки')
align: str = gql.field(default='left', description='Выравнивание')
type: str = gql.field(default='string', description='Тип ячейки')


class TableRowType(ObjectType):
@gql.type
class TableRowType:
"""Строка документа."""

index = graphene.Int(required=True, description='Индекс строки')
cells = graphene.List(TableCellType, required=True, description='Строка документа')
index: int = gql.field(description='Индекс строки')
cells: list[TableCellType] = gql.field(description='Строка документа')


class TableType(ObjectType):
@gql.type
class TableType:
"""Документ, представлющий собой таблицу."""

headers = graphene.List(graphene.String, required=True, description='Заголовки документа')
rows = graphene.List(TableRowType, required=True, description='Строки документа')
headers: list[str] = gql.field(description='Заголовки документа')
rows: list[TableRowType] = gql.field(description='Строки документа')

@classmethod
def from_iff(cls, iff: ImportFromFile):
Expand All @@ -62,22 +47,24 @@ def from_iff(cls, iff: ImportFromFile):
:param iff: класс импорта данных из файла
"""

rows: List[TableRowType] = []
rows: list[TableRowType] = []
for index, item in enumerate(iff.initial_items):
r = flatten(item, reducer='dot')
rows.append(TableRowType(index=index, cells=[TableCellType(header=k, value=v) for k, v in r.items()]))
return cls(headers=iff.all_keys, rows=rows)


class SetSettingsInputType(graphene.InputObjectType):
@gql.input
class SetSettingsInputType:
"""Настройка для установки."""

key = graphene.String(required=True, description='Ключ настройки')
value = graphene.String(required=True, description='Значение настройки')
user_id = graphene.ID(description='Пользователь к которому применяется настройка')
key: str = gql.field(description='Ключ настройки')
value: str = gql.field(description='Значение настройки')
user_id: gql.ID = gql.field(description='Пользователь к которому применяется настройка')


class ActionRelationShip(graphene.Enum):
@gql.enum
class ActionRelationShip(enum.Enum):
"""Типы измнения связей между записями в базе данных
- ADD - Добавление
- DELETE - Удаление
Expand All @@ -87,7 +74,8 @@ class ActionRelationShip(graphene.Enum):
DELETE = 2


class ConsumerActionType(graphene.Enum):
@gql.enum
class ConsumerActionType(enum.Enum):
"""Типы уведомления пользователей
- CONNECT - Присоединился
- DISCONNECT - Отсоединился
Expand All @@ -108,4 +96,4 @@ class ConsumerActionType(graphene.Enum):
ERROR = 6
TYPING = 7
TYPING_FINISH = 8
EXCEPTION = 9
EXCEPTION = 9
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ license = "MIT"
readme = "readme.md"
homepage = "https://github.com/devind-team/devind-django-helpers"
repository = "https://github.com/devind-team/devind-django-helpers"
keywords = ["django", "graphene", "helpers"]
keywords = ["django", "helpers"]
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
Expand All @@ -24,6 +24,7 @@ inflection = "^0.5.1"
flatten-dict = "^0.4.2"
openpyxl = "^3.0.10"
graphql-core = "^3.2.1"
strawberry-django-plus = "^1.17.0"

[tool.poetry.dev-dependencies]

Expand Down

0 comments on commit fbfe36a

Please sign in to comment.