实战教程

保护环境变量中的 CaptchaAI 凭证

在源代码中硬编码 API 密钥意味着具有存储库访问权限的任何人(或在公共存储库上找到您的代码的任何人)都拥有您的密钥。环境变量将凭证保留在代码、版本控制和日志之外。


.env 文件(本地开发)

在项目根目录中创建 .env 文件:

CAPTCHAAI_API_KEY=your_actual_api_key_here

立即将其添加到.gitignore

# .gitignore
.env
.env.local
.env.production

Python(python-dotenv)

pip install python-dotenv
import os
from dotenv import load_dotenv

load_dotenv()

API_KEY = os.environ["CAPTCHAAI_API_KEY"]

# Use in API calls
import requests
resp = requests.post("https://ocr.captchaai.com/in.php", data={
    "key": API_KEY,
    "method": "userrecaptcha",
    "googlekey": "6Le-SITEKEY",
    "pageurl": "https://example.com",
    "json": "1",
})
print(resp.json())

JavaScript(点环境)

npm install dotenv
require('dotenv').config();

const API_KEY = process.env.CAPTCHAAI_API_KEY;

if (!API_KEY) {
  console.error('CAPTCHAAI_API_KEY not set');
  process.exit(1);
}

// Use in API calls
const axios = require('axios');
const resp = await axios.post('https://ocr.captchaai.com/in.php', null, {
  params: {
    key: API_KEY,
    method: 'userrecaptcha',
    googlekey: '6Le-SITEKEY',
    pageurl: 'https://example.com',
    json: 1,
  },
});
console.log(resp.data);

系统环境变量

在操作系统级别设置变量而不是使用 .env 文件:

Linux / macOS

export CAPTCHAAI_API_KEY="your_actual_api_key_here"

# Persist across sessions — add to ~/.bashrc or ~/.zshrc
echo 'export CAPTCHAAI_API_KEY="your_actual_api_key_here"' >> ~/.bashrc

Windows(PowerShell)

$env:CAPTCHAAI_API_KEY = "your_actual_api_key_here"

# Persist permanently
[System.Environment]::SetEnvironmentVariable("CAPTCHAAI_API_KEY", "your_actual_api_key_here", "User")

码头工人

docker run 中的环境变量

docker run -e CAPTCHAAI_API_KEY="your_key" my-scraper

Docker 组合

# docker-compose.yml
services:
  scraper:
    image: my-scraper
    environment:

      - CAPTCHAAI_API_KEY=${CAPTCHAAI_API_KEY}

${CAPTCHAAI_API_KEY} 引用主机的环境变量 - 该密钥永远不会出现在撰写文件中。

Docker 的秘密(Swarm)

echo "your_actual_api_key_here" | docker secret create captchaai_key -
# docker-compose.yml (Swarm mode)
services:
  scraper:
    image: my-scraper
    secrets:

      - captchaai_key
secrets:
  captchaai_key:
    external: true

读入代码:

with open("/run/secrets/captchaai_key") as f:
    API_KEY = f.read().strip()

CI/CD 管道

GitHub 操作

# .github/workflows/scrape.yml
jobs:
  scrape:
    runs-on: ubuntu-latest
    steps:

      - uses: actions/checkout@v4
      - run: python scraper.py
        env:
          CAPTCHAAI_API_KEY: ${{ secrets.CAPTCHAAI_API_KEY }}

设置→秘密和变量→操作→新存储库秘密中添加秘密。

亚搏体育appGitLab持续集成

# .gitlab-ci.yml
scrape:
  script:

    - python scraper.py
  variables:
    CAPTCHAAI_API_KEY: $CAPTCHAAI_API_KEY

设置 → CI/CD → 变量 中添加变量,并启用“屏蔽”选项。


启动时验证

在运行管道之前,请始终验证密钥是否存在并且有效:

import os
import sys
import requests

API_KEY = os.environ.get("CAPTCHAAI_API_KEY")
if not API_KEY:
    print("ERROR: CAPTCHAAI_API_KEY environment variable not set")
    sys.exit(1)

# Verify key works
resp = requests.get("https://ocr.captchaai.com/res.php", params={
    "key": API_KEY, "action": "getbalance", "json": "1"
}).json()

if resp["status"] != 1:
    print(f"ERROR: Invalid API key — {resp['request']}")
    sys.exit(1)

print(f"API key valid — balance: ${float(resp['request']):.2f}")

常见错误

错误 风险 处理方式
.env 提交到 Git 回购历史记录中暴露的密钥 在第一次提交之前将 .env 添加到 .gitignore
在日志中打印 API 密钥 键在日志聚合器中可见 切勿记录完整密钥 - 屏蔽或省略它们
Dockerfile 中的硬编码 将关键帧烘焙到图像层中 在运行时使用 ENV,而不是在构建阶段
通过聊天共享密钥/email 密钥被拦截或泄露 使用机密管理器或通过安全通道共享

常问问题

我应该加密 .env 文件吗?

对于本地开发,.gitignore 就足够了。对于生产,请使用云机密管理器(AWS Secrets Manager、Google Secret Manager、Azure Key Vault)而不是 .env 文件。

如果我的密钥已经提交给 Git 怎么办?

立即在 CaptchaAI 仪表板中旋转钥匙。即使删除文件后,Git 历史记录中的旧密钥仍然可以访问。

我可以在一个 .env 文件中使用多个密钥吗?

是的。使用逗号分隔值或编号键:

CAPTCHAAI_KEYS=key1,key2,key3
keys = os.environ["CAPTCHAAI_KEYS"].split(",")

从第一天起保护您的 CaptchaAI 集成

获取您的 API 密钥:验证码网站


相关指南

该文章已禁用评论。