Skip to content

Commit c7af29e

Browse files
Merge pull request #1 from captcha-solver-api/ci/ruff
ci: add ruff lint and format checks
2 parents 64e8a45 + 8c33aeb commit c7af29e

52 files changed

Lines changed: 812 additions & 595 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/publish.yml‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,14 @@ permissions:
1010
contents: read
1111

1212
jobs:
13+
# Reuse the full lint + test workflow so a release never ships from a
14+
# broken tree, even if the tag was pushed without a CI run on the commit.
1315
test:
1416
uses: ./.github/workflows/tests.yml
1517

18+
# Build sdist and wheel once and hand them to the publish job as an
19+
# artifact, so what gets uploaded to PyPI is exactly what was built here.
20+
# Also fails fast if the git tag disagrees with _version.py.
1621
build:
1722
needs: test
1823
runs-on: ubuntu-latest
@@ -46,10 +51,13 @@ jobs:
4651
name: dist
4752
path: dist/
4853

54+
# Upload the built artifacts to PyPI via trusted publishing, then create
55+
# the matching GitHub Release with auto-generated notes and the same
56+
# sdist/wheel attached. Only runs on an actual version tag --
57+
# workflow_dispatch runs stop at the build/test stage so you can dry-run
58+
# the release without shipping it.
4959
publish:
5060
needs: build
51-
# Only publish on an actual version tag -- workflow_dispatch runs stop at
52-
# the build/test stage so you can dry-run the release without shipping it.
5361
if: startsWith(github.ref, 'refs/tags/')
5462
runs-on: ubuntu-latest
5563
environment:
@@ -59,6 +67,8 @@ jobs:
5967
# Required for PyPI's trusted publishing (OIDC) -- no API token/secret needed.
6068
# Configure this repo as a trusted publisher at https://pypi.org/manage/project/captcha-solver-api/settings/publishing/
6169
id-token: write
70+
# Required to create the GitHub Release.
71+
contents: write
6272
steps:
6373
- name: Download build artifacts
6474
uses: actions/download-artifact@v4
@@ -68,3 +78,11 @@ jobs:
6878

6979
- name: Publish to PyPI
7080
uses: pypa/gh-action-pypi-publish@release/v1
81+
82+
- name: Create GitHub Release
83+
uses: softprops/action-gh-release@v2
84+
with:
85+
generate_release_notes: true
86+
files: dist/*
87+
# Requires Discussions enabled in the repo with this category present.
88+
discussion_category_name: Announcements

‎.github/workflows/tests.yml‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,43 @@
11
name: Tests
22

33
on:
4+
# Run on pushes to main only; feature branches are covered by the
5+
# pull_request trigger, so this avoids a duplicate run per commit.
46
push:
7+
branches: [main]
58
pull_request:
69
workflow_call:
710

811
jobs:
12+
# Static checks: ruff lint + formatting and mypy type checking. Runs once
13+
# on a single Python version since the result does not depend on the
14+
# interpreter.
15+
lint:
16+
runs-on: ubuntu-latest
17+
steps:
18+
- uses: actions/checkout@v4
19+
20+
- name: Set up Python
21+
uses: actions/setup-python@v5
22+
with:
23+
python-version: "3.12"
24+
25+
- name: Install package with dev dependencies
26+
run: python -m pip install -e ".[dev]"
27+
28+
- name: Ruff lint
29+
run: ruff check .
30+
31+
- name: Ruff format check
32+
run: ruff format --check .
33+
34+
- name: mypy
35+
run: mypy captcha_solver_api
36+
37+
# Test suite across all supported Python versions, plus a build check
38+
# to catch packaging errors early. Skipped if lint fails to save CI minutes.
939
test:
40+
needs: lint
1041
runs-on: ubuntu-latest
1142
strategy:
1243
matrix:

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
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)
12+
[![Checked with mypy](https://www.mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)
13+
[![GitHub Release](https://img.shields.io/github/v/release/captcha-solver-api/python-sdk)](https://github.com/captcha-solver-api/python-sdk/releases)
1114
[![JavaScript SDK](https://img.shields.io/badge/also_available-JavaScript_SDK-f7df1e?logo=javascript&logoColor=black)](https://github.com/captcha-solver-api/javascript-sdk)
1215

1316
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: 10 additions & 5 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:
@@ -113,6 +113,8 @@ async def _request(
113113
except ValueError as exc:
114114
raise NetworkError(f"Non-JSON response from API: {response.text[:200]!r}") from exc
115115

116+
if not isinstance(data, dict):
117+
raise NetworkError(f"Unexpected API response shape: {type(data).__name__}")
116118
return data
117119

118120
def _ensure_success(self, data: Dict[str, Any]) -> None:
@@ -154,7 +156,7 @@ async def create_task(self, task: Any, language_pool: Optional[str] = None) -> i
154156

155157
data = await self._request("createTask", payload)
156158
self._ensure_success(data)
157-
return data["taskId"]
159+
return int(data["taskId"])
158160

159161
async def get_task_result(self, task_id: int) -> Dict[str, Any]:
160162
"""Fetch the current status of a previously submitted task.
@@ -203,7 +205,7 @@ async def get_balance(self) -> float:
203205
payload = {"clientKey": self.client_key}
204206
data = await self._request("getBalance", payload)
205207
self._ensure_success(data)
206-
return data["balance"]
208+
return float(data["balance"])
207209

208210
async def solve(
209211
self,
@@ -248,6 +250,9 @@ async def solve(
248250
result = await self.get_task_result(task_id)
249251

250252
if result.get("status") == "ready":
251-
return result["solution"]
253+
solution = result["solution"]
254+
if not isinstance(solution, dict):
255+
raise NetworkError("API returned a ready task without a solution object")
256+
return solution
252257

253258
raise CaptchaTimeoutError("Task solving timed out.")

‎captcha_solver_api/client.py‎

Lines changed: 10 additions & 5 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:
@@ -102,6 +102,8 @@ def _request(
102102
except ValueError as exc:
103103
raise NetworkError(f"Non-JSON response from API: {response.text[:200]!r}") from exc
104104

105+
if not isinstance(data, dict):
106+
raise NetworkError(f"Unexpected API response shape: {type(data).__name__}")
105107
return data
106108

107109
def _ensure_success(self, data: Dict[str, Any]) -> None:
@@ -141,7 +143,7 @@ def create_task(self, task: Any, language_pool: Optional[str] = None) -> int:
141143

142144
data = self._request("createTask", payload)
143145
self._ensure_success(data)
144-
return data["taskId"]
146+
return int(data["taskId"])
145147

146148
def get_task_result(self, task_id: int) -> Dict[str, Any]:
147149
"""Fetches the current status of a task created with `create_task()`.
@@ -187,7 +189,7 @@ def get_balance(self) -> float:
187189
payload = {"clientKey": self.client_key}
188190
data = self._request("getBalance", payload)
189191
self._ensure_success(data)
190-
return data["balance"]
192+
return float(data["balance"])
191193

192194
def solve(
193195
self,
@@ -230,6 +232,9 @@ def solve(
230232
result = self.get_task_result(task_id)
231233

232234
if result.get("status") == "ready":
233-
return result["solution"]
235+
solution = result["solution"]
236+
if not isinstance(solution, dict):
237+
raise NetworkError("API returned a ready task without a solution object")
238+
return solution
234239

235240
raise CaptchaTimeoutError("Task solving timed out.")

‎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

0 commit comments

Comments
 (0)