Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simple flake8 refactoring #108

Merged
merged 12 commits into from
Jan 5, 2024
8 changes: 5 additions & 3 deletions .flake8
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
[flake8]
exclude =
venv,
.env,
.venv,
venv,
.git,
.gitignore,
README.md,
migrations,
.git,

max-line-length = 99
extend-ignore = F401, E402
extend-ignore = F401, E402, D10
20 changes: 5 additions & 15 deletions functions/event/extra_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@


async def add_events_to_user(call: CallbackQuery, event_id: int) -> None:
"""
Функция, сохраняющая id мероприятий, которые лайкнул пользователь
"""
"""Функция, сохраняющая id мероприятий, которые лайкнул пользователь."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
user = await db_commands.select_user(telegram_id=call.from_user.id)
event_list = user.events

Expand All @@ -23,16 +21,12 @@ async def add_events_to_user(call: CallbackQuery, event_id: int) -> None:


async def check_availability_on_event() -> bool:
"""
Функция, которая проверяет наличие свободных мест на мероприятие
"""
"""Функция, которая проверяет наличие свободных мест на мероприятие."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
...


async def check_event_date(telegram_id: int) -> None:
"""
Функция, которая проверяет - прошло мероприятие или нет
"""
"""Функция, которая проверяет - прошло мероприятие или нет."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
event = await db_commands.select_user_meetings(telegram_id)
event_time = event.time_event
if event_time is None:
Expand Down Expand Up @@ -60,9 +54,7 @@ async def check_event_date(telegram_id: int) -> None:
async def create_form(
form_owner: int, chat_id: int, call: CallbackQuery, view: Union[bool, None] = True
) -> None:
"""
Функция, которая заполняет анкету текстом
"""
"""Функция, которая заполняет анкету текстом."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
try:
owner = await db_commands.select_user_meetings(telegram_id=form_owner)
document = {
Expand All @@ -89,9 +81,7 @@ async def create_form(


async def get_next_random_event_id(telegram_id: int) -> Optional[int]:
"""
Функция, возвращающая случайный id мероприятия, созданного другим пользователем
"""
"""Функция, возвращающая случайный id мероприятия, созданного другим пользователем."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
event_ids = await db_commands.search_event_forms()

other_events_ids = []
Expand Down
20 changes: 5 additions & 15 deletions functions/main_app/auxiliary_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@ async def delete_message(message: Message) -> None:


async def choice_gender(call: CallbackQuery) -> None:
"""
Функция, сохраняющая в базу пол, который выбрал пользователь
"""
"""Функция, сохраняющая в базу пол, который выбрал пользователь."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
sex_mapping = {"male": "Мужской", "female": "Женский"}

selected_sex = sex_mapping.get(call.data)
Expand All @@ -59,9 +57,7 @@ async def choice_gender(call: CallbackQuery) -> None:


async def display_profile(call: CallbackQuery, markup: InlineKeyboardMarkup) -> None:
"""
Функция для отображения профиля пользователя
"""
"""Функция для отображения профиля пользователя."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
user = await db_commands.select_user(telegram_id=call.from_user.id)
count_referrals = await db_commands.count_all_users_kwarg(
referrer_id=call.from_user.id
Expand Down Expand Up @@ -205,9 +201,7 @@ async def finished_registration(
async def saving_normal_photo(
message: Message, telegram_id: int, file_id: int, state: FSMContext
) -> None:
"""
Функция, сохраняющая фотографию пользователя без цензуры
"""
"""Функция, сохраняющая фотографию пользователя без цензуры."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
try:
await db_commands.update_user_data(telegram_id=telegram_id, photo_id=file_id)

Expand All @@ -233,9 +227,7 @@ async def saving_censored_photo(
flag: Optional[str] = "registration",
markup: Union[InlineKeyboardMarkup, None] = None,
) -> None:
"""
Функция, сохраняющая фотографию пользователя с цензурой
"""
""".Функция, сохраняющая фотографию пользователя с цензурой."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
photo = InputFile(out_path)
id_photo = await bot.send_photo(
chat_id=telegram_id,
Expand Down Expand Up @@ -274,9 +266,7 @@ async def saving_censored_photo(
async def update_normal_photo(
message: Message, telegram_id: int, file_id: int, state: FSMContext, markup
) -> None:
"""
Функция, которая обновляет фотографию пользователя
"""
"""Функция, которая обновляет фотографию пользователя."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
try:
await db_commands.update_user_data(telegram_id=telegram_id, photo_id=file_id)
await message.answer(
Expand Down
5 changes: 1 addition & 4 deletions functions/main_app/determin_location.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@ async def update_user_data(self: "Location", message: Message):


class Location(AsyncObj):
"""
Класс для определения и сохранения локации пользователя
в различных сценариях.
"""
"""Класс для определения и сохранения локации пользователя в различных сценариях."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved

async def __ainit__(
self, message: Message, strategy: Type[UserDataUpdateStrategy]
Expand Down
10 changes: 7 additions & 3 deletions keyboards/inline/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ async def start_calendar(
self, year: int = datetime.now().year, month: int = datetime.now().month
) -> InlineKeyboardMarkup:
"""
Creates an inline keyboard with the provided year and month
Create an inline keyboard with the provided year and month.

:param int year: Year to use in the calendar, if None the current year is used.
:param int month: Month to use in the calendar, if None the current month is used.
:return: Returns InlineKeyboardMarkup object with the calendar.
Expand Down Expand Up @@ -119,8 +120,11 @@ async def process_selection(
self, query: CallbackQuery, data: CallbackData
) -> tuple:
"""
Process the callback_query. This method generates a new calendar if forward or
backward is pressed. This method should be called inside a CallbackQueryHandler.
Process the callback_query.

This method generates a new calendar if forward or backward is pressed.
This method should be called inside a CallbackQueryHandler.

:param query: callback_query, as provided by the CallbackQueryHandler
:param data: callback_data, dictionary, set by calendar_callback
:return: Returns a tuple (Boolean,datetime), indicating if a date is selected
Expand Down
8 changes: 2 additions & 6 deletions utils/db_api/db_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,9 +232,7 @@ def select_setting_tech_work():

@sync_to_async
def check_returned_event_id(telegram_id: int, id_of_events_seen: int) -> bool:
"""
Функция, проверяющая, был ли ранее возвращен данный event_id для данного telegram_id
"""
"""Функция, проверяющая, был ли ранее возвращен данный event_id для данного telegram_id."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
returned_event = User.objects.filter(telegram_id=telegram_id).first()
event_list = returned_event.id_of_events_seen

Expand All @@ -243,9 +241,7 @@ def check_returned_event_id(telegram_id: int, id_of_events_seen: int) -> bool:

@sync_to_async
def add_returned_event_id(telegram_id: int, id_of_events_seen: int):
"""
Функция, добавляющая возвращенный event_id для данного telegram_id в базу данных
"""
"""Функция, добавляющая возвращенный event_id для данного telegram_id в базу данных."""
DavidRomanovizc marked this conversation as resolved.
Show resolved Hide resolved
returned_event, created = User.objects.get_or_create(telegram_id=telegram_id)
returned_event.id_of_events_seen.append(id_of_events_seen)
returned_event.save()
Expand Down
10 changes: 6 additions & 4 deletions utils/misc/AsyncObj.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@
class AsyncObj:
def __init__(self, *args, **kwargs):
"""
Standard constructor used for arguments pass
Do not override. Use __ainit__ instead
Init.

Standard constructor used for arguments pass.
Do not override. Use __ainit__ instead.
"""
self.__stored_args = args, kwargs
self.async_initialized = False

async def __ainit__(self, *args, **kwargs) -> None:
"""Async constructor, you should implement this"""
"""Async constructor, you should implement this."""

async def __initobj(self) -> "AsyncObj":
"""Crutch used for __await__ after spawning"""
"""Crutch used for __await__ after spawning."""
assert not self.async_initialized
self.async_initialized = True
# pass the parameters to __ainit__ that passed to __init__
Expand Down
4 changes: 3 additions & 1 deletion utils/misc/profanityFilter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

def censored_message(message) -> str:
"""
This function working only with english words
Get censored message.

This function only works with English words.
"""
censored_text = profanity.censor(message)
return censored_text
2 changes: 2 additions & 0 deletions utils/misc/throttling.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
def rate_limit(limit: int, key=None):
"""
Rate limit decorator.

Decorator for configuring rate limit and key in different functions.

:param limit:
Expand Down
3 changes: 2 additions & 1 deletion utils/yoomoney/types/account_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ class LinkedCard(BaseModel):

class AccountInfo(BaseModel):
"""
Получение информации о состоянии счета пользователя
Получение информации о состоянии счета пользователя.

https://yoomoney.ru/docs/wallet/user-account/account-info
"""

Expand Down
3 changes: 2 additions & 1 deletion utils/yoomoney/types/operation_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

class OperationDetails(BaseModel):
"""
Детальная информация об операции из истории
Детальная информация об операции из истории.

https://yoomoney.ru/docs/wallet/user-account/operation-details
"""

Expand Down
3 changes: 2 additions & 1 deletion utils/yoomoney/types/operation_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

class Operation(BaseModel):
"""
Описание платежной операции
Описание платежной операции.

https://yoomoney.ru/docs/wallet/user-account/operation-history#response-operation
"""

Expand Down
1 change: 1 addition & 0 deletions utils/yoomoney/wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ async def get_operation_history(
) -> list[Operation, ...]:
"""
Получение последних 30 операций.

На 10.03.2023 API yoomoney напросто игнорирует указанные в документации параметры

https://yoomoney.ru/docs/payment-buttons/using-api/forms?lang=ru#parameters
Expand Down
Loading