Integration guide for Python applications using Flask.
Full Example
A complete working example is available on GitHub: Captchacat-Integrations/Python-Flask
Django
For Django-specific integration, see the Django guide.
Requirements#
flask
requestsConfiguration#
Set your Captchacat credentials:
CAPTCHACAT_API_KEY = "" # Your API key
CAPTCHACAT_SITE_KEY = "" # Your site keyValidation Function#
Create a function to validate the CAPTCHA token:
import requests
def validate_captcha_token(token: str) -> bool:
"""Validate the CAPTCHA token with the server."""
if not token:
return False
try:
response = requests.post(
"https://challenge.captchacat.com/validate_token",
json={
"api_key": CAPTCHACAT_API_KEY,
"token": token
},
timeout=10
)
return response.ok
except requests.RequestException:
return FalseTemplate#
Create a form template with the widget:
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<script src="https://challenge.captchacat.com/ray/widget.js"></script>
</head>
<body>
<form action="/submit" method="POST">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<div class="captcha-widget" data-sitekey="{{ site_key }}"></div>
<button type="submit">Sign In</button>
</form>
</body>
</html>Flask Routes#
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html", site_key=CAPTCHACAT_SITE_KEY)
@app.route("/submit", methods=["POST"])
def submit():
token = request.form.get("captchacat-token", "")
if not validate_captcha_token(token):
return "CAPTCHA verification failed", 400
# Token valid - process the form
username = request.form.get("username")
# ... handle form data
return "Login successful!"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)