Skip to content

Commit

Permalink
Rename CommandMultiPartParser class to MultiPartJSONParser and update it
Browse files Browse the repository at this point in the history
  • Loading branch information
EXG1O committed May 10, 2024
1 parent 2eb0779 commit e2097d9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
26 changes: 12 additions & 14 deletions telegram_bots/parsers.py → constructor_telegram_bots/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import json


class CommandMultiPartParser(MultiPartParser):
class MultiPartJSONParser(MultiPartParser):
"""Parser for JSON data in multipart form data with support for files."""

def parse(self, *args: Any, **kwargs: Any) -> dict[str, Any]: # type: ignore [override]
parsed: DataAndFiles = super().parse(*args, **kwargs) # type: ignore [type-arg]

Expand All @@ -17,22 +19,18 @@ def parse(self, *args: Any, **kwargs: Any) -> dict[str, Any]: # type: ignore [o
except (KeyError, JSONDecodeError):
raise ParseError()

sorted_files: dict[str, list[InMemoryUploadedFile | int]] = {
'images': [],
'images_id': [],
'files': [],
'files_id': [],
}
data.update({'images': [], 'images_id': [], 'files': [], 'files_id': []})

for key, value in parsed.files:
name: str = key.split(':')[0] + 's'
for key, value in parsed.files.items():
try:
name: str = key.split(':')[0]
except IndexError:
continue

if name in sorted_files:
if name in ['image', 'file']:
if isinstance(value, InMemoryUploadedFile):
sorted_files[name].append(value)
data[f'{name}s'].append(value)
elif isinstance(value, str) and value.isdigit():
sorted_files[f'{name}_id'].append(int(value))

data.update(sorted_files)
data[f'{name}s_id'].append(int(value))

return data
4 changes: 2 additions & 2 deletions telegram_bots/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

from constructor_telegram_bots.authentication import CookiesTokenAuthentication
from constructor_telegram_bots.pagination import LimitOffsetPagination
from constructor_telegram_bots.parsers import MultiPartJSONParser

from .mixins import TelegramBotMixin
from .models import (
Expand All @@ -32,7 +33,6 @@
User,
Variable,
)
from .parsers import CommandMultiPartParser
from .serializers import (
BackgroundTaskSerializer,
CommandSerializer,
Expand Down Expand Up @@ -116,7 +116,7 @@ def get_queryset(self) -> QuerySet[Connection]:
class CommandViewSet(TelegramBotMixin, ModelViewSet[Command]):
authentication_classes = [CookiesTokenAuthentication]
permission_classes = [IsAuthenticated]
parser_classes = [CommandMultiPartParser]
parser_classes = [MultiPartJSONParser]
lookup_value_converter = 'int'
lookup_field = 'id'

Expand Down

0 comments on commit e2097d9

Please sign in to comment.