Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,16 @@ Usage

To use this library do you need `Anticaptcha.com`_ API key.

You can pass the key explicitly or set the ``ANTICAPTCHA_API_KEY`` environment variable:

.. code:: python

# Explicit key
client = AnticaptchaClient("my-api-key")

# Or set ANTICAPTCHA_API_KEY environment variable
client = AnticaptchaClient()

Solve recaptcha
###############

Expand Down
11 changes: 9 additions & 2 deletions python_anticaptcha/base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import os
import requests
import time
import json
Expand Down Expand Up @@ -89,9 +90,15 @@ class AnticaptchaClient:
response_timeout = 5

def __init__(
self, client_key: str, language_pool: str = "en", host: str = "api.anti-captcha.com", use_ssl: bool = True,
self, client_key: str | None = None, language_pool: str = "en", host: str = "api.anti-captcha.com", use_ssl: bool = True,
) -> None:
self.client_key = client_key
self.client_key = client_key or os.environ.get("ANTICAPTCHA_API_KEY")
if not self.client_key:
raise AnticaptchaException(
None,
"CONFIG_ERROR",
"API key required. Pass client_key or set ANTICAPTCHA_API_KEY env var.",
)
self.language_pool = language_pool
self.base_url = "{proto}://{host}/".format(
proto="https" if use_ssl else "http", host=host
Expand Down
17 changes: 17 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from unittest.mock import patch, MagicMock
import os
import pytest

from python_anticaptcha.base import AnticaptchaClient, Job, SLEEP_EVERY_CHECK_FINISHED
Expand All @@ -23,6 +24,22 @@ def test_language_pool(self):
client = AnticaptchaClient("key123", language_pool="rn")
assert client.language_pool == "rn"

def test_env_var_fallback(self, monkeypatch):
monkeypatch.setenv("ANTICAPTCHA_API_KEY", "env-key-456")
client = AnticaptchaClient()
assert client.client_key == "env-key-456"

def test_explicit_key_over_env(self, monkeypatch):
monkeypatch.setenv("ANTICAPTCHA_API_KEY", "env-key-456")
client = AnticaptchaClient("explicit-key-789")
assert client.client_key == "explicit-key-789"

def test_no_key_raises(self, monkeypatch):
monkeypatch.delenv("ANTICAPTCHA_API_KEY", raising=False)
with pytest.raises(AnticaptchaException) as exc_info:
AnticaptchaClient()
assert exc_info.value.error_code == "CONFIG_ERROR"


class TestCheckResponse:
def setup_method(self):
Expand Down
Loading