Chaves de API e tempos limite codificados funcionam para protótipos. A produção precisa de configuração específica do ambiente, gerenciamento de segredos e capacidade de alterar configurações sem reimplantar.
Hierarquia de configuração
Priority (highest → lowest):
1. Environment variables ← deployment-specific overrides
2. Config file (YAML/JSON) ← version-controlled defaults
3. Application defaults ← fallback values in code
Referência completa de configuração
| Parâmetro | Variável ambiental | Padrão | Descrição |
|---|---|---|---|
| Chave de API | CAPTCHAAI_API_KEY |
- | Obrigatório. Sua chave de API CaptchaAI |
| Enviar URL | CAPTCHAAI_SUBMIT_URL |
https://ocr.captchaai.com/in.php |
Endpoint de envio de tarefa |
| URL da enquete | CAPTCHAAI_POLL_URL |
https://ocr.captchaai.com/res.php |
Ponto de extremidade da pesquisa de resultados |
| Intervalo de pesquisa | CAPTCHAAI_POLL_INTERVAL |
5 |
Segundos entre tentativas de votação |
| Máximo de tentativas de enquete | CAPTCHAAI_MAX_POLLS |
60 |
Máximo de tentativas de sondagem antes do tempo limite |
| Simultaneidade | CAPTCHAAI_CONCURRENCY |
10 |
Máximo de tarefas CAPTCHA paralelas |
| Tempo limite | CAPTCHAAI_TIMEOUT |
300 |
Tempo limite geral em segundos |
| Procurador | CAPTCHAAI_PROXY |
- | URL proxy para resolução de CAPTCHA |
| URL de retorno de chamada | CAPTCHAAI_CALLBACK_URL |
- | URL do webhook para resultados assíncronos |
| Tentar novamente | CAPTCHAAI_RETRIES |
3 |
Novas tentativas em falhas transitórias |
| Nível de registro | CAPTCHAAI_LOG_LEVEL |
info |
Logging verbosidade |
Carregador de configuração
Pitão
import os
import yaml
from dataclasses import dataclass, field
from pathlib import Path
@dataclass
class CaptchaAIConfig:
api_key: str = ""
submit_url: str = "https://ocr.captchaai.com/in.php"
poll_url: str = "https://ocr.captchaai.com/res.php"
poll_interval: int = 5
max_polls: int = 60
concurrency: int = 10
timeout: int = 300
proxy: str = ""
callback_url: str = ""
retries: int = 3
log_level: str = "info"
@classmethod
def load(cls, config_path=None):
"""Load config: env vars override file, which overrides defaults."""
config = cls()
# Layer 2: Config file
if config_path and Path(config_path).exists():
with open(config_path) as f:
file_config = yaml.safe_load(f) or {}
for key, value in file_config.items():
if hasattr(config, key):
setattr(config, key, value)
# Layer 1: Environment variables (highest priority)
env_map = {
"CAPTCHAAI_API_KEY": "api_key",
"CAPTCHAAI_SUBMIT_URL": "submit_url",
"CAPTCHAAI_POLL_URL": "poll_url",
"CAPTCHAAI_POLL_INTERVAL": "poll_interval",
"CAPTCHAAI_MAX_POLLS": "max_polls",
"CAPTCHAAI_CONCURRENCY": "concurrency",
"CAPTCHAAI_TIMEOUT": "timeout",
"CAPTCHAAI_PROXY": "proxy",
"CAPTCHAAI_CALLBACK_URL": "callback_url",
"CAPTCHAAI_RETRIES": "retries",
"CAPTCHAAI_LOG_LEVEL": "log_level",
}
for env_key, attr_name in env_map.items():
value = os.environ.get(env_key)
if value is not None:
# Cast to correct type
current = getattr(config, attr_name)
if isinstance(current, int):
value = int(value)
setattr(config, attr_name, value)
config.validate()
return config
def validate(self):
if not self.api_key:
raise ValueError("CAPTCHAAI_API_KEY is required")
if self.poll_interval < 1:
raise ValueError("poll_interval must be >= 1")
if self.concurrency < 1:
raise ValueError("concurrency must be >= 1")
# Usage
config = CaptchaAIConfig.load("config/captchaai.yaml")
print(f"Concurrency: {config.concurrency}, Timeout: {config.timeout}s")
JavaScript
const fs = require("fs");
const yaml = require("js-yaml");
const path = require("path");
class CaptchaAIConfig {
static defaults = {
apiKey: "",
submitUrl: "https://ocr.captchaai.com/in.php",
pollUrl: "https://ocr.captchaai.com/res.php",
pollInterval: 5,
maxPolls: 60,
concurrency: 10,
timeout: 300,
proxy: "",
callbackUrl: "",
retries: 3,
logLevel: "info",
};
static envMap = {
CAPTCHAAI_API_KEY: "apiKey",
CAPTCHAAI_SUBMIT_URL: "submitUrl",
CAPTCHAAI_POLL_URL: "pollUrl",
CAPTCHAAI_POLL_INTERVAL: { key: "pollInterval", type: "int" },
CAPTCHAAI_MAX_POLLS: { key: "maxPolls", type: "int" },
CAPTCHAAI_CONCURRENCY: { key: "concurrency", type: "int" },
CAPTCHAAI_TIMEOUT: { key: "timeout", type: "int" },
CAPTCHAAI_PROXY: "proxy",
CAPTCHAAI_CALLBACK_URL: "callbackUrl",
CAPTCHAAI_RETRIES: { key: "retries", type: "int" },
CAPTCHAAI_LOG_LEVEL: "logLevel",
};
static load(configPath = null) {
let config = { ...CaptchaAIConfig.defaults };
// Layer 2: Config file
if (configPath && fs.existsSync(configPath)) {
const ext = path.extname(configPath);
const raw = fs.readFileSync(configPath, "utf8");
const fileConfig = ext === ".json" ? JSON.parse(raw) : yaml.load(raw);
config = { ...config, ...fileConfig };
}
// Layer 1: Environment variables
for (const [envKey, mapping] of Object.entries(CaptchaAIConfig.envMap)) {
const value = process.env[envKey];
if (value !== undefined) {
const attrKey = typeof mapping === "string" ? mapping : mapping.key;
const type = typeof mapping === "string" ? "string" : mapping.type;
config[attrKey] = type === "int" ? parseInt(value, 10) : value;
}
}
CaptchaAIConfig.validate(config);
return config;
}
static validate(config) {
if (!config.apiKey) throw new Error("CAPTCHAAI_API_KEY is required");
if (config.pollInterval < 1) throw new Error("pollInterval must be >= 1");
if (config.concurrency < 1) throw new Error("concurrency must be >= 1");
}
}
// Usage
const config = CaptchaAIConfig.load("config/captchaai.yaml");
console.log(`Concurrency: ${config.concurrency}, Timeout: ${config.timeout}s`);
Arquivos de configuração por ambiente
# config/captchaai.yaml — base
api_key: "" # Always set via env var
concurrency: 5
poll_interval: 5
retries: 3
log_level: info
# config/captchaai.production.yaml
concurrency: 20
poll_interval: 3
timeout: 180
log_level: warning
# config/captchaai.staging.yaml
concurrency: 3
poll_interval: 5
timeout: 300
log_level: debug
Gerenciamento de segredos
Nunca armazene chaves de API em arquivos de configuração ou controle de origem.
| Método | mais adequado para | Exemplo |
|---|---|---|
| Variáveis de ambiente | Contêineres, CI/CD | export CAPTCHAAI_API_KEY=abc123 |
| Gerenciador de segredos da AWS | Infraestrutura AWS | Buscar na inicialização; rotação automática |
| Cofre HashiCorp | Várias nuvens, no local | Segredos dinâmicos com TTL |
| Segredos do Docker | Docker Swarm / Compor | Montado em /run/secrets/ |
Arquivo .env (somente dev) |
Desenvolvimento local | Biblioteca dotenv; .gitignore isso |
Exemplo de composição do Docker
services:
captcha-worker:
image: captcha-worker:latest
environment:
- CAPTCHAAI_API_KEY=${CAPTCHAAI_API_KEY}
- CAPTCHAAI_CONCURRENCY=15
- CAPTCHAAI_LOG_LEVEL=warning
env_file:
- .env.production
Sinalizadores de recursos
Alternar recursos sem reimplantar:
class FeatureFlags:
def __init__(self):
self.flags = {
"use_callback": os.environ.get("FF_USE_CALLBACK", "false") == "true",
"enable_proxy": os.environ.get("FF_ENABLE_PROXY", "true") == "true",
"max_concurrent": int(os.environ.get("FF_MAX_CONCURRENT", "10")),
}
def is_enabled(self, flag):
return self.flags.get(flag, False)
def get(self, flag, default=None):
return self.flags.get(flag, default)
Solução de problemas
| Problema | Causa | Correção |
|---|---|---|
| Chave de API não carrega | Variável de ambiente ausente; nome de variável errado | Verifique echo $CAPTCHAAI_API_KEY; verificar a ortografia |
| Arquivo de configuração ignorado | Caminho errado ou biblioteca YAML ausente | Verifique se o arquivo existe; instalar pyyaml / js-yaml |
| Prod usando configurações de desenvolvimento | Substituição específica do ambiente não aplicada | Verifique a precedência do env var; verificar NODE_ENV / APP_ENV |
| Segredos visíveis nos registros | O despejo de configuração inclui chave de API | Mascarar campos confidenciais na saída de log |
Perguntas frequentes
Devo usar YAML ou JSON para arquivos de configuração?
YAML para arquivos editados por humanos (suporta comentários). JSON para configurações geradas por máquina ou quando você deseja uma análise rigorosa.
Com que frequência devo alternar as chaves de API?
Gire imediatamente se estiver comprometido. Programe a rotação a cada 90 dias para conformidade. Use gerenciadores de segredos que suportam rotação automática.
Posso alterar a simultaneidade sem reiniciar?
Sim – leia as configurações das variáveis de ambiente ou de um serviço de configuração em cada lote de tarefas, não apenas na inicialização. Isso permite ajustar a simultaneidade atualizando o env var e enviando um sinal de recarga.
Artigos relacionados
- Configuração do Socks5 Proxy Captchaai
- Captchaai Teams Gerenciamento de chaves de API multiusuário
- Guia de configuração do proxy Captchaai
Próximas etapas
Prepare sua configuração para produção —comece com uma chave de API CaptchaAIe crie a partir dos modelos de configuração acima.
Guias relacionados:
- Segurança de chave de API e lista de permissões de IP
- Solução Docker Containerizada
- Arquitetura multirregional