Python Server SDK
Official Python server-side SDK, published as captchala on PyPI. Sync and async clients, fully typed.
Three jobs the SDK handles for you:
- Validate: verify a
pt_pass token from the browser or native SDK. - Issue: mint a one-time
sct_server token to bind the upcoming challenge to a specific action / IP / user. - Moderate: multi-modal (text + image) content moderation.
Install
pip install captchala # sync client, standard library only
pip install "captchala[async]" # + AsyncClient (httpx)
pip install "captchala[django]" # + Django helpers
pip install "captchala[flask]" # + Flask helpersRequires Python ≥ 3.9.
Validate (pt_ token)
Pass the end-user's IP as client_ip. Optional, but recommended: it's used for additional risk checks.
from captchala import Client
# Reads CAPTCHALA_APP_KEY / CAPTCHALA_APP_SECRET when not passed.
captchala = Client("your_app_key", "your_app_secret")
result = captchala.validate(
token,
client_ip=user_ip,
expected_action="login", # optional: action_mismatch otherwise
expected_hostname="www.example.com", # optional: hostname_mismatch otherwise
)
if not result.valid:
return {"error": result.error}, 400 # e.g. "token_expired"
# Verification passed; proceed with the request.
# result.captcha_args has platform / user_ip / referer / pkg / solved_at / risk_scorevalidate() never raises for invalid tokens, API errors or network failures. Check result.valid and result.error. For API or network failures, result.cause holds a typed exception (NetworkError, RequestTimeoutError, AuthenticationError, RateLimitError, …).
Async:
from captchala import AsyncClient
async with AsyncClient() as captchala:
result = await captchala.validate(token, client_ip=user_ip)If you issued the original server_token with bind_uid, compare the uid returned with the user you actually expect:
if result.uid != expected_user_id:
return "user mismatch", 400You can also send the end-user identity (bind_uid, bind_account, bind_email, bind_phone, scene) to validate() and check result.binding_mismatch.
Django and Flask
# Django: settings.CAPTCHALA_APP_KEY / CAPTCHALA_APP_SECRET
from captchala.contrib.django import CaptchaLaField, CaptchaLaFormMixin, captchala_required
class LoginForm(CaptchaLaFormMixin, forms.Form):
captcha_token = CaptchaLaField(expected_action="login") # cleaned_data -> ValidateResult
@captchala_required(action="login") # sync or async views; sets request.captchala
def login_view(request): ...# Flask: app.config CAPTCHALA_APP_KEY / CAPTCHALA_APP_SECRET
from captchala.contrib.flask import CaptchaLa
captcha = CaptchaLa(app)
@app.post("/login")
@captcha.required(action="login") # sets g.captchala
def login(): ...The helpers read the token from the captcha_token / captchala_token field or the X-Captcha-Token header, and answer HTTP 400 {"error":"captcha_failed","code":"…"} on failure. user_message(code) gives a user-safe text for form errors.
Retries and timeouts
timeout (default 5 s) applies per attempt; max_retries (default 2) retries connection failures and HTTP 502 / 503 / 504 with exponential backoff. Rate-limit answers are not retried; see result.retry_after. Moderation calls are not retried after a timeout.
Client-only tokens (outage fallback)
When the CaptchaLa API can't be reached, the client SDK can still finish the challenge and hand back a client-only token (prefix client_ or co_). It is accepted only if the API is unreachable from your server as well; otherwise it is rejected with error="client_only_rejected_api_reachable". An accepted token is marked client_only=True.
The reachability result is cached (30 s when reachable, 5 s when not), and concurrent validations share a single check.
For sensitive actions (login, payment) you can refuse client-only tokens even during an outage:
strict = Client(reject_client_only=True)
# client_ / co_ -> valid=False, error="client_only_rejected_by_policy"Issue a server token
For high-value flows (login, register, payment) the recommended pattern is: the backend mints a one-time sct_ token, hands it to the browser, and the browser passes it as the serverToken prop.
issue = captchala.issue_server_token(
"login",
bind_ip=user_ip, # optional; see the note on private relays in the API reference
ttl=300, # seconds; default 300
max_uses=5,
bind_uid=str(user.id), # pair with result.uid on verify
)
if not issue.ok:
return {"error": issue.error}, 503 # rate_limit_exceeded, ...
return {"server_token": issue.token} # hand to browserModerate content
from captchala import text_item, image_url_item
result = captchala.moderation_check(
[text_item(user_comment), image_url_item(uploaded_image_url)],
user_id=str(user.id),
)
if not result.ok:
return {"error": result.error}
if result.flagged and result.has_category("violence", "csam"):
... # hard block
# Plain-text shortcut
text = captchala.moderation_text("user comment here")Categories are model-defined; iterate result.categories defensively rather than hard-coding a fixed set.
Testing
Use the public test keys to exercise your server's handling without solving a CAPTCHA. Results from them have test == True. In unit tests, pass a transport callable to Client, or an httpx.AsyncClient with a mock transport to AsyncClient.
Result types
| Type | Fields |
|---|---|
ValidateResult | valid, error, message, action, uid, challenge_id, hostname, challenge_ts, risk_level, risk_labels, captcha_args, user_ip, binding, binding_match, binding_mismatch, degraded, degraded_reason, offline, client_only, warning, test, http_status, retry_after, retryable, cause, raw; raise_if_invalid(), to_dict() |
IssueResult | ok, token, expires_in, issued_at, error, message, http_status, retry_after, retryable, cause |
ModerationResult | ok, flagged, categories, category_scores, content_type, raw, error, message, cause; has_category(*names) |