CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-recaptcha

Django form field and widget integration for Google reCAPTCHA services, supporting reCAPTCHA V2 and V3.

Pending
Overview
Eval results
Files

client-api.mddocs/

Client API

Low-level client interface for direct interaction with Google's reCAPTCHA verification API. Provides functions for submitting reCAPTCHA responses for validation and handling API responses with comprehensive error handling and proxy support.

Capabilities

RecaptchaResponse

Data class encapsulating the response from Google's reCAPTCHA verification API. Contains validation results, error information, and additional data such as V3 scores and actions.

class RecaptchaResponse:
    """
    Response object from reCAPTCHA API verification.
    
    Contains validation results and additional response data.
    """
    
    def __init__(self, is_valid, error_codes=None, extra_data=None, action=None):
        """
        Initialize reCAPTCHA response.
        
        Parameters:
        - is_valid (bool): Whether reCAPTCHA validation passed
        - error_codes (list[str], optional): List of error codes from API response
        - extra_data (dict, optional): Additional response data (score, challenge_ts, etc.)
        - action (str, optional): reCAPTCHA V3 action name from response
        """
        
    # Attributes
    is_valid: bool  # Validation result
    error_codes: list[str]  # Error codes from API
    extra_data: dict  # Additional response data
    action: str | None  # V3 action name

API Submission

Core function for submitting reCAPTCHA responses to Google's verification endpoint. Handles HTTP communication, proxy configuration, and response parsing.

def submit(recaptcha_response, private_key, remoteip):
    """
    Submit reCAPTCHA response for verification.
    
    Makes HTTP POST request to Google's verification API and returns
    parsed response data.
    
    Parameters:
    - recaptcha_response (str): reCAPTCHA response token from client
    - private_key (str): Google reCAPTCHA private key
    - remoteip (str): Client IP address for verification
    
    Returns:
    RecaptchaResponse: Parsed API response with validation results
    
    Raises:
    HTTPError: If API request fails (timeout, network error, etc.)
    """

HTTP Request Handling

Low-level function for making HTTP requests to Google's reCAPTCHA API with proxy support and custom headers.

def recaptcha_request(params):
    """
    Make HTTP request to reCAPTCHA API endpoint.
    
    Handles proxy configuration, custom headers, and timeout settings.
    
    Parameters:
    - params (bytes): URL-encoded parameters for API request
    
    Returns:
    HTTPResponse: Raw HTTP response from API
    
    Configuration:
    - Uses RECAPTCHA_DOMAIN setting for API endpoint
    - Supports RECAPTCHA_PROXY setting for proxy configuration
    - Uses RECAPTCHA_VERIFY_REQUEST_TIMEOUT for request timeout
    """

API Response Data

Successful Response

For valid reCAPTCHA responses, the API returns:

  • success: true - Validation passed
  • challenge_ts - Timestamp of challenge completion
  • hostname - Hostname of site where reCAPTCHA was solved
  • score (V3 only) - Risk score from 0.0 to 1.0
  • action (V3 only) - Action name from request

Error Response

For invalid responses, the API returns error codes:

  • missing-input-secret - Secret parameter missing
  • invalid-input-secret - Secret parameter invalid
  • missing-input-response - Response parameter missing
  • invalid-input-response - Response parameter invalid
  • bad-request - Request invalid or malformed
  • timeout-or-duplicate - Response timed out or previously used

Configuration

The client respects Django settings for API configuration:

  • RECAPTCHA_DOMAIN: API domain (default: "www.google.com")
  • RECAPTCHA_PROXY: Proxy configuration dictionary
  • RECAPTCHA_VERIFY_REQUEST_TIMEOUT: Request timeout in seconds (default: 10)

Usage Examples

Direct API Usage

from django_recaptcha.client import submit

# Submit reCAPTCHA response for verification
response = submit(
    recaptcha_response="03AHJ_ASjdkjf...",  # From form submission
    private_key="6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe",
    remoteip="192.168.1.100"
)

if response.is_valid:
    print("reCAPTCHA validation passed")
    if response.extra_data.get('score'):
        print(f"V3 Score: {response.extra_data['score']}")
else:
    print(f"Validation failed: {response.error_codes}")

Custom Validation Logic

from django_recaptcha.client import submit
from django.core.exceptions import ValidationError

def validate_recaptcha(token, private_key, client_ip):
    """Custom reCAPTCHA validation with error handling."""
    try:
        response = submit(token, private_key, client_ip)
        
        if not response.is_valid:
            raise ValidationError(
                f"reCAPTCHA validation failed: {', '.join(response.error_codes)}"
            )
            
        # V3 score validation
        if 'score' in response.extra_data:
            score = response.extra_data['score']
            if score < 0.5:
                raise ValidationError(
                    f"reCAPTCHA score too low: {score}"
                )
                
        return response
        
    except HTTPError as e:
        raise ValidationError("reCAPTCHA API communication error")

Response Data Access

response = submit(token, private_key, client_ip)

# Basic validation
if response.is_valid:
    print("Valid reCAPTCHA")

# Error handling
if response.error_codes:
    for error in response.error_codes:
        print(f"Error: {error}")

# V3 specific data
if response.action:
    print(f"Action: {response.action}")

if 'score' in response.extra_data:
    score = response.extra_data['score']
    print(f"Risk score: {score}")

# Additional metadata
if 'challenge_ts' in response.extra_data:
    timestamp = response.extra_data['challenge_ts']
    print(f"Challenge completed at: {timestamp}")

Low-level Request Handling

from django_recaptcha.client import recaptcha_request
from urllib.parse import urlencode
import json

# Prepare request parameters
params = urlencode({
    'secret': 'your_private_key',
    'response': 'recaptcha_response_token',
    'remoteip': '192.168.1.100'
}).encode('utf-8')

# Make direct API request
try:
    http_response = recaptcha_request(params)
    data = json.loads(http_response.read().decode('utf-8'))
    http_response.close()
    
    print(f"API Response: {data}")
    
except Exception as e:
    print(f"Request failed: {e}")

Install with Tessl CLI

npx tessl i tessl/pypi-django-recaptcha

docs

client-api.md

configuration.md

form-fields.md

index.md

widgets.md

tile.json