Skip to content

Commit

Permalink
Update ruff settings
Browse files Browse the repository at this point in the history
  • Loading branch information
EXG1O committed May 6, 2024
1 parent 9d0e4ed commit ce673cb
Show file tree
Hide file tree
Showing 26 changed files with 472 additions and 278 deletions.
2 changes: 1 addition & 1 deletion constructor_telegram_bots/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@
INSTALLED_APPS.append('silk')

REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'drf_standardized_errors.handler.exception_handler',
'EXCEPTION_HANDLER': 'drf_standardized_errors.handler.exception_handler'
}

TINYMCE_DEFAULT_CONFIG = {
Expand Down
4 changes: 3 additions & 1 deletion constructor_telegram_bots/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,6 @@

urlpatterns.append(path('silk/', include('silk.urls', namespace='silk')))

urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='frontend/index.html'))]
urlpatterns += [
re_path(r'^.*', TemplateView.as_view(template_name='frontend/index.html'))
]
8 changes: 6 additions & 2 deletions donation/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ def section_position_default() -> int:
class Section(models.Model): # type: ignore [django-manager-missing]
title = models.CharField(_('Заголовок'), max_length=255)
text = models.TextField(_('Текст'))
position = models.PositiveSmallIntegerField(_('Позиция'), blank=True, default=section_position_default)
position = models.PositiveSmallIntegerField(
_('Позиция'), blank=True, default=section_position_default
)

class Meta(TypedModelMeta):
ordering = ['position']
Expand All @@ -46,7 +48,9 @@ def button_position_default() -> int:
class Button(models.Model): # type: ignore [django-manager-missing]
text = models.CharField(_('Текст'), max_length=255)
url = models.URLField(_('Ссылка'))
position = models.PositiveSmallIntegerField(_('Позиция'), blank=True, default=button_position_default)
position = models.PositiveSmallIntegerField(
_('Позиция'), blank=True, default=button_position_default
)

class Meta(TypedModelMeta):
ordering = ['position']
Expand Down
4 changes: 3 additions & 1 deletion instruction/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ def section_position_default() -> int:
class Section(models.Model): # type: ignore [django-manager-missing]
title = models.CharField(_('Заголовок'), max_length=255)
text = models.TextField(_('Текст'))
position = models.PositiveSmallIntegerField(_('Позиция'), blank=True, default=section_position_default)
position = models.PositiveSmallIntegerField(
_('Позиция'), blank=True, default=section_position_default
)

class Meta(TypedModelMeta):
ordering = ['position']
Expand Down
4 changes: 1 addition & 3 deletions languages/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,4 @@
from .views import LanguagesAPIView

app_name = 'languages'
urlpatterns = [
path('', LanguagesAPIView.as_view(), name='index'),
]
urlpatterns = [path('', LanguagesAPIView.as_view(), name='index')]
4 changes: 3 additions & 1 deletion manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@


def main() -> None:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'constructor_telegram_bots.settings')
os.environ.setdefault(
'DJANGO_SETTINGS_MODULE', 'constructor_telegram_bots.settings'
)

try:
from django.core.management import execute_from_command_line
Expand Down
4 changes: 3 additions & 1 deletion privacy_policy/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ def section_default_position() -> int:
class Section(models.Model): # type: ignore [django-manager-missing]
title = models.CharField(_('Заголовок'), max_length=255)
text = models.TextField(_('Текст'))
position = models.PositiveSmallIntegerField(_('Позиция'), blank=True, default=section_default_position)
position = models.PositiveSmallIntegerField(
_('Позиция'), blank=True, default=section_default_position
)

class Meta(TypedModelMeta):
ordering = ['position']
Expand Down
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,8 @@ plugins = ["mypy_django_plugin.main", "mypy_drf_plugin.main"]
django_settings_module = "constructor_telegram_bots.settings"

[tool.ruff]
line-length = 120
target-version = "py311"
extend-exclude = ["frontend", "migrations"]
extend-exclude = ["migrations"]

[tool.ruff.lint]
select = [
Expand All @@ -53,7 +52,8 @@ select = [
"UP", # pyupgrade
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"T20" # flake8-print
"T20", # flake8-print
"INT", # flake8-gettext
]
ignore = [
"E501", # line too long, handled by black
Expand Down
40 changes: 17 additions & 23 deletions telegram_bots/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ class TelegramBotAdmin(admin.ModelAdmin[TelegramBot]):
list_display = [
'id',
'owner',
'_username',
'_storage_size',
'_used_storage_size',
'_remaining_storage_size',
'username_display',
'storage_size_display',
'used_storage_size_display',
'remaining_storage_size_display',
'commands_count',
'users_count',
'is_private',
Expand All @@ -32,11 +32,11 @@ class TelegramBotAdmin(admin.ModelAdmin[TelegramBot]):
fields = [
'id',
'owner',
'_username',
'username_display',
'api_token',
'_storage_size',
'_used_storage_size',
'_remaining_storage_size',
'storage_size_display',
'used_storage_size_display',
'remaining_storage_size_display',
'commands_count',
'users_count',
'is_private',
Expand All @@ -48,26 +48,25 @@ def get_queryset(self, request: HttpRequest) -> QuerySet[TelegramBot]:
return (
super()
.get_queryset(request)
.annotate(
commands_count=Count('commands'),
users_count=Count('users'),
)
.annotate(commands_count=Count('commands'), users_count=Count('users'))
)

@admin.display(description='@username', ordering='username')
def _username(self, telegram_bot: TelegramBot) -> str:
return format_html_link(f'tg://resolve?domain={telegram_bot.username}', f'@{telegram_bot.username}')
def username_display(self, telegram_bot: TelegramBot) -> str:
return format_html_link(
f'tg://resolve?domain={telegram_bot.username}', f'@{telegram_bot.username}'
)

@admin.display(description=_('Размер хранилища'))
def _storage_size(self, telegram_bot: TelegramBot) -> str:
def storage_size_display(self, telegram_bot: TelegramBot) -> str:
return f'{(telegram_bot.storage_size / 1024 ** 2):.2f}MB'

@admin.display(description=_('Используемый размер хранилища'))
def _used_storage_size(self, telegram_bot: TelegramBot) -> str:
def used_storage_size_display(self, telegram_bot: TelegramBot) -> str:
return f'{(telegram_bot.used_storage_size / 1024 ** 2):.2f}MB'

@admin.display(description=_('Оставшийся размер хранилища'))
def _remaining_storage_size(self, telegram_bot: TelegramBot) -> str:
def remaining_storage_size_display(self, telegram_bot: TelegramBot) -> str:
return f'{(telegram_bot.remaining_storage_size / 1024 ** 2):.2f}MB'

@admin.display(description=_('Команд'), ordering='commands_count')
Expand All @@ -89,12 +88,7 @@ def has_change_permission(self, *args: Any, **kwargs: Any) -> Literal[False]:
class UserAdmin(admin.ModelAdmin[User]):
search_fields = ['telegram_id', 'full_name']
date_hierarchy = 'activated_date'
list_filter = [
'is_allowed',
'is_blocked',
'last_activity_date',
'activated_date',
]
list_filter = ['is_allowed', 'is_blocked', 'last_activity_date', 'activated_date']
list_display = [
'id',
'telegram_bot',
Expand Down
12 changes: 9 additions & 3 deletions telegram_bots/base_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ class AbstractBlock(models.Model):
name = models.CharField(_('Название'), max_length=128)
x = models.FloatField(_('Координата X'), default=0)
y = models.FloatField(_('Координата Y'), default=0)
source_connections = GenericRelation('Connection', 'source_object_id', 'source_content_type')
target_connections = GenericRelation('Connection', 'target_object_id', 'target_content_type')
source_connections = GenericRelation(
'Connection', 'source_object_id', 'source_content_type'
)
target_connections = GenericRelation(
'Connection', 'target_object_id', 'target_content_type'
)

class Meta(TypedModelMeta):
abstract = True
Expand All @@ -29,7 +33,9 @@ class AbstractAPIRequest(models.Model):
]

url = models.URLField(_('URL-адрес'))
method = models.CharField(_('Метод'), max_length=6, choices=METHOD_CHOICES, default='get')
method = models.CharField(
_('Метод'), max_length=6, choices=METHOD_CHOICES, default='get'
)
headers = models.JSONField(_('Заголовки'), blank=True, null=True)
body = models.JSONField(_('Данные'), blank=True, null=True)

Expand Down
4 changes: 3 additions & 1 deletion telegram_bots/hub/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
class TokenAuthentication(BaseTokenAuthentication):
def authenticate_credentials(self, token: str) -> tuple[TelegramBotsHub, str]:
try:
telegram_bots_hub: TelegramBotsHub = TelegramBotsHub.objects.get(token=token)
telegram_bots_hub: TelegramBotsHub = TelegramBotsHub.objects.get(
token=token
)
except TelegramBotsHub.DoesNotExist:
raise AuthenticationFailed(_('Неверный токен!'))

Expand Down
13 changes: 7 additions & 6 deletions telegram_bots/hub/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,9 @@ def is_port_available(self, port: int) -> bool:

@property
def is_available(self) -> bool:
response: Response | None = self.make_api_request('get', '/', delete_on_exception=False)
response: Response | None = self.make_api_request(
'get', '/', delete_on_exception=False
)

if response:
data: dict[str, Any] = response.json()
Expand Down Expand Up @@ -181,10 +183,7 @@ def save(
for _retry in range(10):
if self.is_available:
return super().save(
force_insert,
force_update,
using,
update_fields,
force_insert, force_update, using, update_fields
)

time.sleep(6)
Expand All @@ -193,7 +192,9 @@ def save(
except ProcessLookupError:
pass

def delete(self, using: str | None = None, keep_parents: bool = False) -> tuple[int, dict[str, int]]:
def delete(
self, using: str | None = None, keep_parents: bool = False
) -> tuple[int, dict[str, int]]:
if self.is_available:
os.kill(self.pid, signal.SIGTERM)

Expand Down
22 changes: 17 additions & 5 deletions telegram_bots/hub/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ class Meta:
fields = ('id', 'is_private', 'is_enabled', 'is_loading')
read_only_fields = ('id', 'is_private')

def update(self, instance: TelegramBot, validated_data: dict[str, Any]) -> TelegramBot:
def update(
self, instance: TelegramBot, validated_data: dict[str, Any]
) -> TelegramBot:
instance.is_enabled = validated_data.get('is_enabled', instance.is_enabled)
instance.is_loading = validated_data.get('is_loading', instance.is_loading)
instance.save()
Expand All @@ -36,7 +38,11 @@ def update(self, instance: TelegramBot, validated_data: dict[str, Any]) -> Teleg
class CommandSettingsSerializer(serializers.ModelSerializer[CommandSettings]):
class Meta:
model = CommandSettings
fields = ('is_reply_to_user_message', 'is_delete_user_message', 'is_send_as_new_message')
fields = (
'is_reply_to_user_message',
'is_delete_user_message',
'is_send_as_new_message',
)


class CommandTriggerSerializer(serializers.ModelSerializer[CommandTrigger]):
Expand Down Expand Up @@ -81,7 +87,9 @@ class Meta:
fields = ('text',)


class CommandKeyboardButtonSerializer(serializers.ModelSerializer[CommandKeyboardButton]):
class CommandKeyboardButtonSerializer(
serializers.ModelSerializer[CommandKeyboardButton]
):
telegram_bot_command_id = serializers.IntegerField(source='telegram_bot_command.id')

class Meta:
Expand All @@ -103,7 +111,9 @@ class Meta:
fields = ('url', 'method', 'headers', 'body')


class CommandDatabaseRecordSerializer(serializers.ModelSerializer[CommandDatabaseRecord]):
class CommandDatabaseRecordSerializer(
serializers.ModelSerializer[CommandDatabaseRecord]
):
class Meta:
model = CommandDatabaseRecord
fields = ('data',)
Expand Down Expand Up @@ -152,7 +162,9 @@ def telegram_bot(self) -> TelegramBot:
telegram_bot: TelegramBot | None = self.context.get('telegram_bot')

if not isinstance(telegram_bot, TelegramBot):
raise TypeError('You not passed a TelegramBot instance to the serializer context!')
raise TypeError(
'You not passed a TelegramBot instance to the serializer context!'
)

return telegram_bot

Expand Down
5 changes: 4 additions & 1 deletion telegram_bots/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ class TelegramBotMixin:
@property
def telegram_bot(self) -> TelegramBot:
if self._telegram_bot is None:
self._telegram_bot = get_object_or_404(self.request.user.telegram_bots, id=self.kwargs['telegram_bot_id']) # type: ignore [attr-defined]
self._telegram_bot = get_object_or_404(
self.request.user.telegram_bots, # type: ignore [attr-defined]
id=self.kwargs['telegram_bot_id'], # type: ignore [attr-defined]
)

return self._telegram_bot

Expand Down
Loading

0 comments on commit ce673cb

Please sign in to comment.