Skip to content

Commit

Permalink
Simple flake8 refactoring (DavidRomanovizc#108)
Browse files Browse the repository at this point in the history
* added .venv to flake8 excludes

* added fixed flake D-type exception

* Update functions/event/extra_features.py

Signed-off-by: David Dzhalaev <[email protected]>

* Update functions/event/extra_features.py

Signed-off-by: David Dzhalaev <[email protected]>

* Update functions/event/extra_features.py

Signed-off-by: David Dzhalaev <[email protected]>

* Update functions/event/extra_features.py

Signed-off-by: David Dzhalaev <[email protected]>

* Update functions/event/extra_features.py

Signed-off-by: David Dzhalaev <[email protected]>

* Update functions/main_app/auxiliary_tools.py

Signed-off-by: David Dzhalaev <[email protected]>

* Update functions/main_app/auxiliary_tools.py

Signed-off-by: David Dzhalaev <[email protected]>

* Update utils/db_api/db_commands.py

Signed-off-by: David Dzhalaev <[email protected]>

* Update utils/db_api/db_commands.py

Signed-off-by: David Dzhalaev <[email protected]>

* Update functions/main_app/determin_location.py

Signed-off-by: David Dzhalaev <[email protected]>

---------

Signed-off-by: David Dzhalaev <[email protected]>
Co-authored-by: David Dzhalaev <[email protected]>
  • Loading branch information
nkhaldi and DavidRomanovizc committed Jan 8, 2024
1 parent d79193e commit 97b1441
Show file tree
Hide file tree
Showing 13 changed files with 39 additions and 52 deletions.
2 changes: 1 addition & 1 deletion .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ exclude =
migrations,

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 мероприятий, которые лайкнул пользователь
"""
"""Function that stores id's of events liked by a user."""
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:
"""
Функция, которая проверяет наличие свободных мест на мероприятие
"""
"""Function that checks the availability of seats for an event."""
...


async def check_event_date(telegram_id: int) -> None:
"""
Функция, которая проверяет - прошло мероприятие или нет
"""
"""Function that checks whether an event has passed or not."""
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:
"""
Функция, которая заполняет анкету текстом
"""
""" Function that fills the form with text."""
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 мероприятия, созданного другим пользователем
"""
"""Function that returns a random id of an event created by another user."""
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:
"""
Функция, сохраняющая в базу пол, который выбрал пользователь
"""
"""Function that saves to the database the gender that the user has selected."""
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:
"""
Функция для отображения профиля пользователя
"""
"""Function for displaying the user profile."""
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:
"""
Функция, сохраняющая фотографию пользователя без цензуры
"""
"""Функция, сохраняющая фотографию пользователя без цензуры."""
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:
"""
Функция, сохраняющая фотографию пользователя с цензурой
"""
""".Функция, сохраняющая фотографию пользователя с цензурой."""
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:
"""
Функция, которая обновляет фотографию пользователя
"""
"""Функция, которая обновляет фотографию пользователя."""
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):
"""
Класс для определения и сохранения локации пользователя
в различных сценариях.
"""
"""Class for defining and saving the user's location in various scenarios."""

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
"""
"""Function that checks if the given event_id was previously returned for the given telegram_id."""
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 в базу данных
"""
"""Function that adds the returned event_id for the given telegram_id to the database."""
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

0 comments on commit 97b1441

Please sign in to comment.