Skip to content

Commit e71b0d7

Browse files
ci: add ruff lint and format checks
Add ruff to dev dependencies with a py39-targeted config, run `ruff check --fix` and `ruff format` across the codebase, and add a lint job to the tests workflow that gates the test matrix. Export `__version__` in `__all__` and add the Ruff badge to README. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
1 parent 64e8a45 commit e71b0d7

51 files changed

Lines changed: 754 additions & 587 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/tests.yml‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,27 @@ on:
66
workflow_call:
77

88
jobs:
9+
lint:
10+
runs-on: ubuntu-latest
11+
steps:
12+
- uses: actions/checkout@v4
13+
14+
- name: Set up Python
15+
uses: actions/setup-python@v5
16+
with:
17+
python-version: "3.12"
18+
19+
- name: Install package with dev dependencies
20+
run: python -m pip install -e ".[dev]"
21+
22+
- name: Ruff lint
23+
run: ruff check .
24+
25+
- name: Ruff format check
26+
run: ruff format --check .
27+
928
test:
29+
needs: lint
1030
runs-on: ubuntu-latest
1131
strategy:
1232
matrix:

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
[![Tests](https://github.com/captcha-solver-api/python-sdk/actions/workflows/tests.yml/badge.svg)](https://github.com/captcha-solver-api/python-sdk/actions/workflows/tests.yml)
99
[![Typed](https://img.shields.io/badge/typing-typed-blue)](https://github.com/captcha-solver-api/python-sdk/blob/main/captcha_solver_api/py.typed)
1010
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/captcha-solver-api/python-sdk/blob/main/LICENSE.md)
11+
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
1112
[![JavaScript SDK](https://img.shields.io/badge/also_available-JavaScript_SDK-f7df1e?logo=javascript&logoColor=black)](https://github.com/captcha-solver-api/javascript-sdk)
1213

1314
Official Python SDK for the Captcha Solver API. Solve reCAPTCHA v2/v3, Cloudflare Turnstile, GeeTest, Yandex SmartCaptcha, Tencent, and image/click captchas with a single method call -- sync or async.

‎captcha_solver_api/__init__.py‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,26 +13,26 @@
1313
result = client.solve(task)
1414
"""
1515

16-
from .client import CaptchaClient
16+
from ._version import __version__
1717
from .async_client import AsyncCaptchaClient
18+
from .client import CaptchaClient
1819
from .exceptions import (
19-
CaptchaError,
2020
ApiError,
21-
NetworkError,
21+
CaptchaError,
2222
CaptchaTimeoutError,
23+
NetworkError,
2324
TimeoutError,
2425
ValidationError,
2526
)
2627

27-
from ._version import __version__
28-
2928
__all__ = [
30-
"CaptchaClient",
29+
"ApiError",
3130
"AsyncCaptchaClient",
31+
"CaptchaClient",
3232
"CaptchaError",
33-
"ApiError",
34-
"NetworkError",
3533
"CaptchaTimeoutError",
34+
"NetworkError",
3635
"TimeoutError",
3736
"ValidationError",
37+
"__version__",
3838
]

‎captcha_solver_api/async_client.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
1515
from ._version import __version__
1616
from .exceptions import (
1717
ApiError,
18-
NetworkError,
1918
CaptchaTimeoutError,
19+
NetworkError,
2020
ValidationError,
2121
)
2222

@@ -87,7 +87,7 @@ async def aclose(self) -> None:
8787
(`async with AsyncCaptchaClient(...) as c:`) to have it closed automatically."""
8888
await self._client.aclose()
8989

90-
async def __aenter__(self) -> "AsyncCaptchaClient":
90+
async def __aenter__(self) -> AsyncCaptchaClient:
9191
return self
9292

9393
async def __aexit__(self, *exc_info: Any) -> None:

‎captcha_solver_api/client.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
from ._version import __version__
1313
from .exceptions import (
1414
ApiError,
15-
NetworkError,
1615
CaptchaTimeoutError,
16+
NetworkError,
1717
ValidationError,
1818
)
1919

@@ -76,7 +76,7 @@ def close(self) -> None:
7676
to have it closed automatically."""
7777
self.session.close()
7878

79-
def __enter__(self) -> "CaptchaClient":
79+
def __enter__(self) -> CaptchaClient:
8080
return self
8181

8282
def __exit__(self, *exc_info: Any) -> None:

‎captcha_solver_api/exceptions.py‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,14 @@
66
class CaptchaError(Exception):
77
"""Base exception for all SDK errors."""
88

9-
pass
10-
119

1210
class NetworkError(CaptchaError):
1311
"""Raised when a network request fails."""
1412

15-
pass
16-
1713

1814
class CaptchaTimeoutError(CaptchaError):
1915
"""Raised when the operation exceeds the configured timeout."""
2016

21-
pass
22-
2317

2418
# Deprecated alias kept for backward compatibility. It shadows the built-in
2519
# ``TimeoutError`` when imported by name, so prefer ``CaptchaTimeoutError``.
@@ -37,5 +31,3 @@ def __init__(self, error_code: str, error_description: str) -> None:
3731

3832
class ValidationError(CaptchaError):
3933
"""Raised for client-side argument problems caught before any request is sent."""
40-
41-
pass

‎captcha_solver_api/tasks.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
from __future__ import annotations
1414

15-
from typing import Any, Dict, List, Optional
15+
from typing import Any, Dict, Optional
1616

1717

1818
class BaseTask:

‎examples/async/balance.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,14 @@
1313
try:
1414
from dotenv import load_dotenv
1515
except ModuleNotFoundError as exc:
16-
if exc.name != 'dotenv':
16+
if exc.name != "dotenv":
1717
raise
1818
load_dotenv = None
1919

2020
repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
2121
sys.path.append(repo_root)
2222
if load_dotenv is not None:
23-
load_dotenv(os.path.join(repo_root, '.env'))
23+
load_dotenv(os.path.join(repo_root, ".env"))
2424

2525
from captcha_solver_api import AsyncCaptchaClient
2626

@@ -30,7 +30,7 @@
3030
# you can just set the API key directly to its value like:
3131
# api_key="1abc234de56fab7c89012d34e56fa7b8"
3232

33-
api_key = os.getenv('CAPTCHA_API_KEY', 'YOUR_API_KEY')
33+
api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY")
3434

3535
solver = AsyncCaptchaClient(api_key)
3636

@@ -40,7 +40,7 @@ async def main():
4040
# Returns a float with the available amount in your account currency.
4141
try:
4242
balance = await solver.get_balance()
43-
print('Balance: ' + str(balance))
43+
print("Balance: " + str(balance))
4444
except Exception as e:
4545
sys.exit(e)
4646

‎examples/async/coordinates.py‎

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,20 @@
1616
try:
1717
from dotenv import load_dotenv
1818
except ModuleNotFoundError as exc:
19-
if exc.name != 'dotenv':
19+
if exc.name != "dotenv":
2020
raise
2121
load_dotenv = None
2222

2323
repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
2424
sys.path.append(repo_root)
2525
if load_dotenv is not None:
26-
load_dotenv(os.path.join(repo_root, '.env'))
27-
assets_dir = os.path.join(repo_root, 'examples', 'assets')
26+
load_dotenv(os.path.join(repo_root, ".env"))
27+
assets_dir = os.path.join(repo_root, "examples", "assets")
2828

2929
from captcha_solver_api import AsyncCaptchaClient
3030
from captcha_solver_api.tasks import CoordinatesTask
3131

32-
api_key = os.getenv('CAPTCHA_API_KEY', 'YOUR_API_KEY')
32+
api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY")
3333

3434
solver = AsyncCaptchaClient(api_key)
3535

@@ -41,41 +41,45 @@ async def main():
4141
try:
4242
# Read and encode the captcha image to base64.
4343
# The body must be a pure base64 string without the data:image/...;base64, prefix.
44-
with open(os.path.join(assets_dir, 'fruit-click.png'), 'rb') as f:
45-
body = b64encode(f.read()).decode('utf-8')
44+
with open(os.path.join(assets_dir, "fruit-click.png"), "rb") as f:
45+
body = b64encode(f.read()).decode("utf-8")
4646

47-
result = await solver.solve(CoordinatesTask(
48-
body=body, # Base64-encoded captcha image (required)
49-
comment='click on the green apple', # Text hint for the worker
50-
))
47+
result = await solver.solve(
48+
CoordinatesTask(
49+
body=body, # Base64-encoded captcha image (required)
50+
comment="click on the green apple", # Text hint for the worker
51+
)
52+
)
5153
# Solution contains {"coordinates": [{"x": 140, "y": 110}]}
5254
# Click on each coordinate in order. Coordinates are pixel positions.
53-
print('result: ' + str(result))
55+
print("result: " + str(result))
5456
except Exception as e:
5557
sys.exit(e)
5658

5759
# --- Advanced example ---
5860
# Solves a captcha (examples/assets/traffic-lights.png) with instruction image
5961
# and click count limits.
6062
try:
61-
with open(os.path.join(assets_dir, 'traffic-lights.png'), 'rb') as f:
62-
body = b64encode(f.read()).decode('utf-8')
63+
with open(os.path.join(assets_dir, "traffic-lights.png"), "rb") as f:
64+
body = b64encode(f.read()).decode("utf-8")
6365

6466
# Read and encode an optional instruction image.
6567
# This image helps the worker understand what to click.
66-
with open(os.path.join(assets_dir, 'traffic-lights-instructions.png'), 'rb') as f:
67-
img_instructions = b64encode(f.read()).decode('utf-8')
68+
with open(os.path.join(assets_dir, "traffic-lights-instructions.png"), "rb") as f:
69+
img_instructions = b64encode(f.read()).decode("utf-8")
6870

69-
result = await solver.solve(CoordinatesTask(
70-
body=body, # Base64-encoded captcha image
71-
comment='click on all traffic lights', # Text hint for the worker
72-
imgInstructions=img_instructions, # Optional instruction image
73-
minClicks=1, # Minimum number of clicks (default 1)
74-
maxClicks=3, # Maximum number of clicks allowed
75-
))
71+
result = await solver.solve(
72+
CoordinatesTask(
73+
body=body, # Base64-encoded captcha image
74+
comment="click on all traffic lights", # Text hint for the worker
75+
imgInstructions=img_instructions, # Optional instruction image
76+
minClicks=1, # Minimum number of clicks (default 1)
77+
maxClicks=3, # Maximum number of clicks allowed
78+
)
79+
)
7680
# Solution contains coordinates for all requested clicks, e.g.
7781
# {"coordinates": [{"x": 110, "y": 150}, {"x": 430, "y": 130}]}
78-
print('result: ' + str(result))
82+
print("result: " + str(result))
7983
except Exception as e:
8084
sys.exit(e)
8185

‎examples/async/geetest_v3.py‎

Lines changed: 33 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,23 @@
1717
import sys
1818

1919
import httpx
20+
2021
try:
2122
from dotenv import load_dotenv
2223
except ModuleNotFoundError as exc:
23-
if exc.name != 'dotenv':
24+
if exc.name != "dotenv":
2425
raise
2526
load_dotenv = None
2627

2728
repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
2829
sys.path.append(repo_root)
2930
if load_dotenv is not None:
30-
load_dotenv(os.path.join(repo_root, '.env'))
31+
load_dotenv(os.path.join(repo_root, ".env"))
3132

3233
from captcha_solver_api import AsyncCaptchaClient
33-
from captcha_solver_api.tasks import GeeTestTaskProxyless, GeeTestTask
34+
from captcha_solver_api.tasks import GeeTestTask, GeeTestTaskProxyless
3435

35-
api_key = os.getenv('CAPTCHA_API_KEY', 'YOUR_API_KEY')
36+
api_key = os.getenv("CAPTCHA_API_KEY", "YOUR_API_KEY")
3637

3738
# GeeTest tasks may take longer. Increase timeout if needed.
3839
solver = AsyncCaptchaClient(api_key, timeout=300, polling_interval=10)
@@ -48,43 +49,47 @@ async def main():
4849
# In production, extract this from the page's initGeetest call or network requests.
4950
# "target-site.com" is a placeholder -- point this at your real target before running.
5051
async with httpx.AsyncClient() as client:
51-
resp = await client.get('https://target-site.com/path/to/geetest/init', timeout=30)
52-
challenge = resp.json()['challenge']
52+
resp = await client.get("https://target-site.com/path/to/geetest/init", timeout=30)
53+
challenge = resp.json()["challenge"]
5354

5455
# --- Proxyless example ---
5556
# Solves GeeTest v3 without a proxy.
5657
# v3 is the default version, so the version field can be omitted.
5758
try:
58-
result = await solver.solve(GeeTestTaskProxyless(
59-
websiteURL='https://example.com/login', # Full URL of the page with GeeTest
60-
gt='f2ae6cadcf7886856696c46d84d109d1', # Public key of the GeeTest widget
61-
challenge=challenge, # Session-specific value, must be fresh
62-
# Optional fields
63-
# geetestApiServerSubdomain='api-na.geetest.com', # Custom API subdomain
64-
# initParameters={...}, # Extra params from initGeetest call
65-
# userAgent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...', # Browser User-Agent
66-
))
59+
result = await solver.solve(
60+
GeeTestTaskProxyless(
61+
websiteURL="https://example.com/login", # Full URL of the page with GeeTest
62+
gt="f2ae6cadcf7886856696c46d84d109d1", # Public key of the GeeTest widget
63+
challenge=challenge, # Session-specific value, must be fresh
64+
# Optional fields
65+
# geetestApiServerSubdomain='api-na.geetest.com', # Custom API subdomain
66+
# initParameters={...}, # Extra params from initGeetest call
67+
# userAgent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...', # Browser User-Agent
68+
)
69+
)
6770
# Solution contains {"challenge": "...", "validate": "...", "seccode": "..."}
6871
# Pass solution.validate and solution.seccode to the page's GeeTest callback.
69-
print('result: ' + str(result))
72+
print("result: " + str(result))
7073
except Exception as e:
7174
sys.exit(e)
7275

7376
# --- With proxy example ---
7477
# Solves GeeTest v3 through your own proxy.
7578
try:
76-
result = await solver.solve(GeeTestTask(
77-
websiteURL='https://example.com/login', # Full URL of the page with GeeTest
78-
gt='f2ae6cadcf7886856696c46d84d109d1', # Public key of the GeeTest widget
79-
challenge=challenge, # Session-specific value, must be fresh
80-
# --- Proxy parameters (replace with your own -- these are placeholders) ---
81-
proxyType='http', # http, socks4, or socks5
82-
proxyAddress='1.2.3.4', # Proxy IP address
83-
proxyPort=8080, # Proxy port
84-
proxyLogin='user', # Login for proxy authorization (optional)
85-
proxyPassword='password', # Password for proxy authorization (optional)
86-
))
87-
print('result: ' + str(result))
79+
result = await solver.solve(
80+
GeeTestTask(
81+
websiteURL="https://example.com/login", # Full URL of the page with GeeTest
82+
gt="f2ae6cadcf7886856696c46d84d109d1", # Public key of the GeeTest widget
83+
challenge=challenge, # Session-specific value, must be fresh
84+
# --- Proxy parameters (replace with your own -- these are placeholders) ---
85+
proxyType="http", # http, socks4, or socks5
86+
proxyAddress="1.2.3.4", # Proxy IP address
87+
proxyPort=8080, # Proxy port
88+
proxyLogin="user", # Login for proxy authorization (optional)
89+
proxyPassword="password", # Password for proxy authorization (optional)
90+
)
91+
)
92+
print("result: " + str(result))
8893
except Exception as e:
8994
sys.exit(e)
9095

0 commit comments

Comments
 (0)