diff --git a/README.rst b/README.rst index efb5a0b..1846064 100644 --- a/README.rst +++ b/README.rst @@ -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 ############### diff --git a/python_anticaptcha/base.py b/python_anticaptcha/base.py index a5188f7..a0014e7 100644 --- a/python_anticaptcha/base.py +++ b/python_anticaptcha/base.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os import requests import time import json @@ -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 diff --git a/tests/test_base.py b/tests/test_base.py index 0582aad..2794b85 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -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 @@ -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):