From 1460607e37867b68d18ff192cc12b034221da679 Mon Sep 17 00:00:00 2001 From: Andrei Date: Wed, 14 Dec 2022 12:42:17 +0300 Subject: [PATCH] refactor --- src/pyproject.toml | 19 +++++++++++-- src/python3_anticaptcha/AntiCaptchaControl.py | 28 +++++-------------- .../FunCaptchaTaskProxyless.py | 8 ++---- src/python3_anticaptcha/ImageToTextTask.py | 27 ++++-------------- src/python3_anticaptcha/NoCaptchaTask.py | 4 +-- .../NoCaptchaTaskProxyless.py | 4 +-- .../ReCaptchaV3TaskProxyless.py | 4 +-- src/python3_anticaptcha/SquareNetTextTask.py | 20 +++---------- src/python3_anticaptcha/core/base.py | 8 ++---- src/python3_anticaptcha/core/errors.py | 4 +-- src/python3_anticaptcha/core/serializer.py | 12 ++------ src/python3_anticaptcha/errors.py | 4 +-- 12 files changed, 45 insertions(+), 97 deletions(-) diff --git a/src/pyproject.toml b/src/pyproject.toml index 07103cd..6c5d122 100644 --- a/src/pyproject.toml +++ b/src/pyproject.toml @@ -1,6 +1,6 @@ [tool.black] -line-length = 110 -target-version = ['py36'] +line-length = 120 +target-version = ['py310'] exclude = ''' /( \.git @@ -13,4 +13,17 @@ exclude = ''' | build | dist )/ -''' \ No newline at end of file +''' + +[tool.isort] +profile = "black" +line_length = 120 +length_sort = true + +[tool.pytest.ini_options] +minversion = "7.0" +asyncio_mode = "auto" +testpaths = [ + "tests", +] +addopts = "-vv --tb=short --durations=5" diff --git a/src/python3_anticaptcha/AntiCaptchaControl.py b/src/python3_anticaptcha/AntiCaptchaControl.py index 31d7353..ab2d270 100644 --- a/src/python3_anticaptcha/AntiCaptchaControl.py +++ b/src/python3_anticaptcha/AntiCaptchaControl.py @@ -81,9 +81,7 @@ class AntiCaptchaControl: answer = requests.post(send_funds_url, json=payload, verify=False) return answer.json() - def get_spend_stats( - self, date: int = None, queue: str = None, softId: int = None, ip: str = None - ) -> dict: + def get_spend_stats(self, date: int = None, queue: str = None, softId: int = None, ip: str = None) -> dict: f""" С помощью этого метода можно получить статистику трат за последние 24 часа. :param date: Unix timestamp начала периода 24-х часового отчета @@ -94,9 +92,7 @@ class AntiCaptchaControl: :return: Возвращает словарь с данными трат """ if queue and queue not in queues_names: - raise ValueError( - f"\nWrong `queue` parameter. Valid params: {queues_names}." f"\n\tYour param - `{queue}`" - ) + raise ValueError(f"\nWrong `queue` parameter. Valid params: {queues_names}." f"\n\tYour param - `{queue}`") payload = { "clientKey": self.ANTICAPTCHA_KEY, "date": date, @@ -180,9 +176,7 @@ class AntiCaptchaControl: """ if queue_id not in queue_ids: - raise ValueError( - f"\nWrong `mode` parameter. Valid params: {queue_ids}." f"\n\tYour param - `{queue_id}`" - ) + raise ValueError(f"\nWrong `mode` parameter. Valid params: {queue_ids}." f"\n\tYour param - `{queue_id}`") payload = {"queueId": queue_id} answer = requests.post(get_queue_status_url, json=payload, verify=False) @@ -218,9 +212,7 @@ class aioAntiCaptchaControl: else: return {"errorId": 1} - async def send_funds( - self, accountLogin: str = None, accountEmail: str = None, amount: float = None - ) -> dict: + async def send_funds(self, accountLogin: str = None, accountEmail: str = None, amount: float = None) -> dict: """ Отправить средства другому пользователю В вашем аккаунте должна быть включена опция отправки средств через API. @@ -244,9 +236,7 @@ class aioAntiCaptchaControl: else: return {"errorId": 1} - async def get_spend_stats( - self, date: int = None, queue: str = None, softId: int = None, ip: str = None - ) -> dict: + async def get_spend_stats(self, date: int = None, queue: str = None, softId: int = None, ip: str = None) -> dict: f""" С помощью этого метода можно получить статистику трат за последние 24 часа. :param date: Unix timestamp начала периода 24-х часового отчета @@ -257,9 +247,7 @@ class aioAntiCaptchaControl: :return: Возвращает словарь с данными трат """ if queue and queue not in queues_names: - raise ValueError( - f"\nWrong `queue` parameter. Valid params: {queues_names}." f"\n\tYour param - `{queue}`" - ) + raise ValueError(f"\nWrong `queue` parameter. Valid params: {queues_names}." f"\n\tYour param - `{queue}`") payload = { "clientKey": self.ANTICAPTCHA_KEY, "date": date, @@ -349,9 +337,7 @@ class aioAntiCaptchaControl: :return: JSON-объект """ if queue_id not in queue_ids: - raise ValueError( - f"\nWrong `mode` parameter. Valid params: {queue_ids}." f"\n\tYour param - `{queue_id}`" - ) + raise ValueError(f"\nWrong `mode` parameter. Valid params: {queue_ids}." f"\n\tYour param - `{queue_id}`") payload = {"queueId": queue_id} async with aiohttp.ClientSession() as session: diff --git a/src/python3_anticaptcha/FunCaptchaTaskProxyless.py b/src/python3_anticaptcha/FunCaptchaTaskProxyless.py index c90d892..b190c6e 100644 --- a/src/python3_anticaptcha/FunCaptchaTaskProxyless.py +++ b/src/python3_anticaptcha/FunCaptchaTaskProxyless.py @@ -51,9 +51,7 @@ class FunCaptchaTaskProxyless: :param kwargs: Дополнительные параметры для `requests.post(....)`. :return: Возвращает ответ сервера в виде JSON(ответ так же можно глянуть в документации антикапчи) """ - self.task_payload["task"].update( - {"websiteURL": websiteURL, "data": data, "websitePublicKey": websitePublicKey} - ) + self.task_payload["task"].update({"websiteURL": websiteURL, "data": data, "websitePublicKey": websitePublicKey}) # Отправляем на антикапча параметры фанкапич, # в результате получаем JSON ответ содержащий номер решаемой капчи captcha_id = requests.post(create_task_url, json=self.task_payload, verify=False, **kwargs).json() @@ -110,9 +108,7 @@ class aioFunCaptchaTaskProxyless: :param websitePublicKey: Ключ капчи(как его получить - описано в документаии на сайте антикапчи) :return: Возвращает ответ сервера в виде JSON(ответ так же можно глянуть в документации антикапчи) """ - self.task_payload["task"].update( - {"websiteURL": websiteURL, "data": data, "websitePublicKey": websitePublicKey} - ) + self.task_payload["task"].update({"websiteURL": websiteURL, "data": data, "websitePublicKey": websitePublicKey}) # Отправляем на антикапча параметры фанкапич, # в результате получаем JSON ответ содержащий номер решаемой капчи async with aiohttp.ClientSession() as session: diff --git a/src/python3_anticaptcha/ImageToTextTask.py b/src/python3_anticaptcha/ImageToTextTask.py index 87537ed..601ab4e 100644 --- a/src/python3_anticaptcha/ImageToTextTask.py +++ b/src/python3_anticaptcha/ImageToTextTask.py @@ -8,14 +8,7 @@ import aiohttp import requests from requests.adapters import HTTPAdapter -from python3_anticaptcha import ( - ReadError, - ParamError, - app_key, - create_task_url, - get_sync_result, - get_async_result, -) +from python3_anticaptcha import ReadError, ParamError, app_key, create_task_url, get_sync_result, get_async_result SAVE_FORMATS = ("const", "temp") @@ -52,8 +45,7 @@ class ImageToTextTask: self.save_format = save_format else: raise ValueError( - f"\nWrong `save_format` parameter. Valid params: {SAVE_FORMATS}." - f"\n\tYour param - `{save_format}`" + f"\nWrong `save_format` parameter. Valid params: {SAVE_FORMATS}." f"\n\tYour param - `{save_format}`" ) # Пайлоад для создания задачи self.task_payload = { @@ -141,9 +133,7 @@ class ImageToTextTask: if content_type == "file": with open(content, "rb") as captcha_image: # Добавляем в пайлоад картинку и отправляем - self.task_payload["task"].update( - {"body": base64.b64encode(captcha_image.read()).decode("utf-8")} - ) + self.task_payload["task"].update({"body": base64.b64encode(captcha_image.read()).decode("utf-8")}) elif content_type == "base64": self.task_payload["task"].update({"body": content}) else: @@ -227,9 +217,7 @@ class ImageToTextTask: else: # Ожидаем решения капчи time.sleep(self.sleep_time) - return get_sync_result( - result_payload=self.result_payload, sleep_time=self.sleep_time, **session_params - ) + return get_sync_result(result_payload=self.result_payload, sleep_time=self.sleep_time, **session_params) class aioImageToTextTask: @@ -264,8 +252,7 @@ class aioImageToTextTask: self.save_format = save_format else: raise ValueError( - f"\nWrong `save_format` parameter. Valid params: {SAVE_FORMATS}." - f"\n\tYour param - `{save_format}`" + f"\nWrong `save_format` parameter. Valid params: {SAVE_FORMATS}." f"\n\tYour param - `{save_format}`" ) # Пайлоад для создания задачи @@ -359,9 +346,7 @@ class aioImageToTextTask: if content_type == "file": with open(content, "rb") as captcha_image: # Добавляем в пайлоад картинку и отправляем - self.task_payload["task"].update( - {"body": base64.b64encode(captcha_image.read()).decode("utf-8")} - ) + self.task_payload["task"].update({"body": base64.b64encode(captcha_image.read()).decode("utf-8")}) elif content_type == "base64": self.task_payload["task"].update({"body": content}) else: diff --git a/src/python3_anticaptcha/NoCaptchaTask.py b/src/python3_anticaptcha/NoCaptchaTask.py index 1707630..feb51a7 100644 --- a/src/python3_anticaptcha/NoCaptchaTask.py +++ b/src/python3_anticaptcha/NoCaptchaTask.py @@ -48,9 +48,7 @@ class NoCaptchaTask: return True # Работа с капчей - def captcha_handler( - self, websiteURL: str, websiteKey: str, recaptchaDataSValue: str = "", **kwargs - ) -> dict: + def captcha_handler(self, websiteURL: str, websiteKey: str, recaptchaDataSValue: str = "", **kwargs) -> dict: """ Метод получает ссылку на страницу, где расположена капча, и ключ капчи :param: websiteURL: Ссылка на страницу с капчёй diff --git a/src/python3_anticaptcha/NoCaptchaTaskProxyless.py b/src/python3_anticaptcha/NoCaptchaTaskProxyless.py index 4f18cfb..368e67b 100644 --- a/src/python3_anticaptcha/NoCaptchaTaskProxyless.py +++ b/src/python3_anticaptcha/NoCaptchaTaskProxyless.py @@ -47,9 +47,7 @@ class NoCaptchaTaskProxyless: return True # Работа с капчёй - def captcha_handler( - self, websiteURL: str, websiteKey: str, recaptchaDataSValue: str = "", **kwargs - ) -> dict: + def captcha_handler(self, websiteURL: str, websiteKey: str, recaptchaDataSValue: str = "", **kwargs) -> dict: """ Метод решения ReCaptcha :param websiteURL: Ссылка на страницу с капчёй diff --git a/src/python3_anticaptcha/ReCaptchaV3TaskProxyless.py b/src/python3_anticaptcha/ReCaptchaV3TaskProxyless.py index 34f8d80..e21d9a0 100644 --- a/src/python3_anticaptcha/ReCaptchaV3TaskProxyless.py +++ b/src/python3_anticaptcha/ReCaptchaV3TaskProxyless.py @@ -135,9 +135,7 @@ class aioReCaptchaV3TaskProxyless: return True # Работа с капчёй - async def captcha_handler( - self, websiteURL: str, websiteKey: str, minScore: float, pageAction: str = None - ) -> dict: + async def captcha_handler(self, websiteURL: str, websiteKey: str, minScore: float, pageAction: str = None) -> dict: """ Метод решения ReCaptcha V3 :param websiteURL: Ссылка на страницу с капчёй diff --git a/src/python3_anticaptcha/SquareNetTextTask.py b/src/python3_anticaptcha/SquareNetTextTask.py index 16ed25c..fd243b1 100644 --- a/src/python3_anticaptcha/SquareNetTextTask.py +++ b/src/python3_anticaptcha/SquareNetTextTask.py @@ -8,14 +8,7 @@ import aiohttp import requests from requests.adapters import HTTPAdapter -from python3_anticaptcha import ( - ReadError, - ParamError, - app_key, - create_task_url, - get_sync_result, - get_async_result, -) +from python3_anticaptcha import ReadError, ParamError, app_key, create_task_url, get_sync_result, get_async_result class SquareNetTextTask: @@ -134,9 +127,7 @@ class SquareNetTextTask: if content_type == "file": with open(content, "rb") as captcha_image: # Добавляем в пайлоад картинку и отправляем - self.task_payload["task"].update( - {"body": base64.b64encode(captcha_image.read()).decode("utf-8")} - ) + self.task_payload["task"].update({"body": base64.b64encode(captcha_image.read()).decode("utf-8")}) elif content_type == "base64": self.task_payload["task"].update({"body": content}) else: @@ -260,8 +251,7 @@ class aioSquareNetTextTask: self.save_format = save_format else: raise ValueError( - "\nWrong `save_format` parameter. Valid params: `const` or `temp`." - f"\n\tYour param - `{save_format}`" + "\nWrong `save_format` parameter. Valid params: `const` or `temp`." f"\n\tYour param - `{save_format}`" ) # Пайлоад для создания задачи self.task_payload = { @@ -348,9 +338,7 @@ class aioSquareNetTextTask: if content_type == "file": with open(content, "rb") as captcha_image: # Добавляем в пайлоад картинку и отправляем - self.task_payload["task"].update( - {"body": base64.b64encode(captcha_image.read()).decode("utf-8")} - ) + self.task_payload["task"].update({"body": base64.b64encode(captcha_image.read()).decode("utf-8")}) elif content_type == "base64": self.task_payload["task"].update({"body": content}) else: diff --git a/src/python3_anticaptcha/core/base.py b/src/python3_anticaptcha/core/base.py index 9efe434..8ac8650 100644 --- a/src/python3_anticaptcha/core/base.py +++ b/src/python3_anticaptcha/core/base.py @@ -40,9 +40,7 @@ class BaseCaptcha: if captcha_type in CaptchaTypeEnm.list_values(): self.captcha_type = captcha_type else: - raise ValueError( - f"Invalid `captcha_type` parameter set, available - {CaptchaTypeEnm.list_values()}" - ) + raise ValueError(f"Invalid `captcha_type` parameter set, available - {CaptchaTypeEnm.list_values()}") self.__sleep_time = sleep_time # assign args to validator @@ -95,9 +93,7 @@ class BaseCaptcha: Function send SYNC request to service and wait for result """ try: - resp = self.__session.post( - parse.urljoin(BASE_REQUEST_URL, CREATE_TASK_POSTFIX), json=self.__params.dict() - ) + resp = self.__session.post(parse.urljoin(BASE_REQUEST_URL, CREATE_TASK_POSTFIX), json=self.__params.dict()) if resp.status_code == 200: return CreateTaskResponseSer(**resp.json()) else: diff --git a/src/python3_anticaptcha/core/errors.py b/src/python3_anticaptcha/core/errors.py index dd1bf49..374a6bd 100644 --- a/src/python3_anticaptcha/core/errors.py +++ b/src/python3_anticaptcha/core/errors.py @@ -22,9 +22,7 @@ class ParamError(AntiCaptchaApiException): def __init__(self, additional_info=None): AntiCaptchaApiException.__init__( self, - """\nПораждается, при передаче неверного параметра.""" + additional_info - if additional_info - else "\n", + """\nПораждается, при передаче неверного параметра.""" + additional_info if additional_info else "\n", ) diff --git a/src/python3_anticaptcha/core/serializer.py b/src/python3_anticaptcha/core/serializer.py index 74d1086..b43ca9e 100644 --- a/src/python3_anticaptcha/core/serializer.py +++ b/src/python3_anticaptcha/core/serializer.py @@ -18,12 +18,8 @@ class BaseAPIResponseSer(BaseModel): class CreateTaskRequestSer(BaseAPIRequestSer): task: Dict = Field(None, description="Task object.") - languagePool: str = Field( - "en", description="Sets workers' pool language. Only applies to image captchas." - ) - callbackUrl: str = Field( - None, description="Web address where we can send the results of captcha task processing." - ) + languagePool: str = Field("en", description="Sets workers' pool language. Only applies to image captchas.") + callbackUrl: str = Field(None, description="Web address where we can send the results of captcha task processing.") softId: int = Field(APP_KEY, const=True) @@ -65,9 +61,7 @@ Captcha tasks serializers class TurnstileProxylessOptionsSer(CreateTaskRequestTaskSer): - websiteURL: str = Field( - ..., description="Address of a target web page. Can be located anywhere on the web site." - ) + websiteURL: str = Field(..., description="Address of a target web page. Can be located anywhere on the web site.") websiteKey: str = Field(..., description="Website key") diff --git a/src/python3_anticaptcha/errors.py b/src/python3_anticaptcha/errors.py index dd1bf49..374a6bd 100644 --- a/src/python3_anticaptcha/errors.py +++ b/src/python3_anticaptcha/errors.py @@ -22,9 +22,7 @@ class ParamError(AntiCaptchaApiException): def __init__(self, additional_info=None): AntiCaptchaApiException.__init__( self, - """\nПораждается, при передаче неверного параметра.""" + additional_info - if additional_info - else "\n", + """\nПораждается, при передаче неверного параметра.""" + additional_info if additional_info else "\n", )