### Install EasyCaptcha-Python
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Install the library using pip or from source. For source installation, clone the repository and use pip install -e.
```bash
pip install easy-captcha-python
```
```bash
git clone https://github.com/Savlgoodman/EasyCaptcha-Python
cd easy-captcha-python
pip install -e .
```
--------------------------------
### Install EasyCaptcha-Python from source
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Clone the repository and install in editable mode for local development.
```bash
git clone https://github.com/Savlgoodman/EasyCaptcha-Python
cd easy-captcha-python
pip install -e .
```
--------------------------------
### Install EasyCaptcha-Python via pip
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Use pip to install the library directly from the package repository.
```bash
pip install easy-captcha-python
```
--------------------------------
### Initialize Flask Application
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Basic setup for a Flask application using EasyCaptcha.
```python
from flask import Flask, jsonify, request
from easy_captcha import SpecCaptcha, GifCaptcha
import uuid
app = Flask(__name__)
```
--------------------------------
### Run Basic Example Script
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/docs/EASYCAPTCHA-PYTHON-USAGE.md
Execute the basic usage example script for easycaptcha-python. This command will generate CAPTCHAs and save them to the ./out/ directory.
```bash
python examples/basic_usage.py
```
--------------------------------
### Setup Flask for Base64 Captcha
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Initial setup for a Flask application intended to return base64 encoded images for frontend-backend separation.
```python
from flask import Flask, jsonify, request
import uuid
app = Flask(__name__)
```
--------------------------------
### Frontend Captcha Integration with JavaScript
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Example of how to fetch a CAPTCHA image and key from the backend and submit login credentials with the verification code using JavaScript.
```html
```
--------------------------------
### Flask Integration for Captcha Generation and Verification
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Provides a complete Flask application example that includes endpoints for generating PNG, GIF, and arithmetic captchas, storing the captcha text in the session, and a verification endpoint to check user input against the stored captcha code.
```python
from flask import Flask, session, make_response, jsonify, request
from easy_captcha import SpecCaptcha, GifCaptcha, ArithmeticCaptcha
from io import BytesIO
import uuid
app = Flask(__name__)
app.secret_key = 'your-secret-key'
# Simple PNG captcha endpoint
@app.route('/captcha')
def captcha():
cap = SpecCaptcha(130, 48, 5)
session['captcha'] = cap.text().lower()
stream = BytesIO()
cap.out(stream)
response = make_response(stream.getvalue())
response.headers['Content-Type'] = 'image/png'
return response
# GIF captcha endpoint
@app.route('/captcha/gif')
def captcha_gif():
cap = GifCaptcha(130, 48, 5)
session['captcha'] = cap.text().lower()
stream = BytesIO()
cap.out(stream)
response = make_response(stream.getvalue())
response.headers['Content-Type'] = 'image/gif'
return response
# Arithmetic captcha endpoint
@app.route('/captcha/arithmetic')
def captcha_arithmetic():
cap = ArithmeticCaptcha(130, 48, 2)
session['captcha'] = cap.text() # Store result, not formula
stream = BytesIO()
cap.out(stream)
response = make_response(stream.getvalue())
response.headers['Content-Type'] = 'image/png'
return response
# Verification endpoint
@app.route('/verify', methods=['POST'])
def verify():
user_input = request.form.get('code', '').lower()
captcha_code = session.get('captcha', '')
if user_input == captcha_code:
session.pop('captcha', None) # Clear after successful verification
return jsonify({'success': True, 'message': 'Verification successful'})
return jsonify({'success': False, 'message': 'Verification failed'})
if __name__ == '__main__':
app.run(debug=True)
```
--------------------------------
### Generate PNG Captcha with SpecCaptcha
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Generates a static PNG CAPTCHA. Use `text()` to get the verification code, `text_char()` for characters, `out()` to save to a file stream, and `to_base64()` for API responses.
```python
from easy_captcha import SpecCaptcha
from io import BytesIO
# Create captcha with width=130, height=48, 5 characters
captcha = SpecCaptcha(130, 48, 5)
# Get the captcha text for verification
code = captcha.text()
print(f"Captcha text: {code}") # Output: Captcha text: A3x9K
# Get characters as a list
chars = captcha.text_char()
print(f"Characters: {chars}") # Output: Characters: ['A', '3', 'x', '9', 'K']
# Output to file
with open('captcha.png', 'wb') as f:
stream = BytesIO()
captcha.out(stream)
f.write(stream.getvalue())
# Output as base64 for API responses
base64_str = captcha.to_base64()
print(f"Base64: {base64_str[:50]}...") # Output: Base64: data:image/png;base64,iVBORw0KGgo...
# Base64 without header prefix
base64_raw = captcha.to_base64("")
```
--------------------------------
### Generate Arithmetic Captcha with ArithmeticCaptcha
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Generates a math problem CAPTCHA. Use `get_arithmetic_string()` to display the formula and `text()` to get the correct result for verification. Supports multiple operands.
```python
from easy_captcha import ArithmeticCaptcha
from io import BytesIO
# Create arithmetic captcha with 2 operands (e.g., "3+5=?")
captcha = ArithmeticCaptcha(130, 48, 2)
# Get the arithmetic formula displayed to user
formula = captcha.get_arithmetic_string()
print(f"Formula: {formula}") # Output: Formula: 3+5=?
# Get the result for verification (store this in session, not the formula)
result = captcha.text()
print(f"Result: {result}") # Output: Result: 8
# Create 3-operand arithmetic captcha (e.g., "2+3x4=?")
captcha3 = ArithmeticCaptcha(150, 48, 3)
captcha3.len = 3 # Set number of operands
formula3 = captcha3.get_arithmetic_string()
result3 = captcha3.text()
print(f"Formula: {formula3}, Result: {result3}") # Output: Formula: 2+3x4=?, Result: 14
# Output to file
with open('arithmetic.png', 'wb') as f:
stream = BytesIO()
captcha.out(stream)
f.write(stream.getvalue())
```
--------------------------------
### Generate Chinese Character Captcha with ChineseCaptcha
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Generates CAPTCHAs using Chinese characters. Use `text()` to get the verification code, `text_char()` for the characters as a list, `out()` to save to a file stream, and `to_base64()` for base64 encoding.
```python
from easy_captcha import ChineseCaptcha
from io import BytesIO
# Create Chinese captcha with 4 characters (default for Chinese)
captcha = ChineseCaptcha(130, 48, 4)
# Get the Chinese verification text
code = captcha.text()
print(f"Captcha text: {code}") # Output: Captcha text: (4 Chinese characters)
# Get characters as list
chars = captcha.text_char()
print(f"Characters: {chars}") # Output: Characters: ['...', '...', '...', '...']
# Output to file
with open('chinese_captcha.png', 'wb') as f:
stream = BytesIO()
captcha.out(stream)
f.write(stream.getvalue())
# Output as base64
base64_str = captcha.to_base64()
```
--------------------------------
### Initialize Different Captcha Types
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Shows how to instantiate various CAPTCHA types including PNG, GIF, Chinese, Chinese GIF, and Arithmetic. For arithmetic CAPTCHAs, 'len' specifies the number of digits.
```python
from easy_captcha import (
SpecCaptcha,GifCaptcha, ChineseCaptcha,
ChineseGifCaptcha, ArithmeticCaptcha
)
# PNG type
captcha = SpecCaptcha(130, 48, 5)
code = captcha.text() # Get captcha text
chars = captcha.text_char() # Get captcha character array
# GIF type
captcha = GifCaptcha(130, 48, 5)
# Chinese type
captcha = ChineseCaptcha(130, 48, 4)
# Chinese GIF type
captcha = ChineseGifCaptcha(130, 48, 4)
# Arithmetic type
captcha = ArithmeticCaptcha(130, 48, 2)
captcha.len = 3 # Number of digits for arithmetic, default is two
formula = captcha.get_arithmetic_string() # Get arithmetic formula: 3+2=?
result = captcha.text() # Get result: 5
```
--------------------------------
### Generate and Verify Captcha with Flask
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Demonstrates how to generate a CAPTCHA and integrate verification into a Flask application. Recommends using Redis for production storage.
```python
captcha_store = {}
@app.route('/captcha')
def get_captcha():
from easy_captcha import SpecCaptcha
cap = SpecCaptcha(130, 48, 5)
code = cap.text().lower()
key = str(uuid.uuid4())
# Store captcha (recommend storing in Redis with expiration in production)
captcha_store[key] = code
# Return key and base64 image
return jsonify({
'key': key,
'image': cap.to_base64()
})
@app.route('/login', methods=['POST'])
def login():
data = request.json
ver_key = data.get('verKey')
ver_code = data.get('verCode', '').lower()
# Verify captcha
if ver_code == captcha_store.get(ver_key):
# Remove after successful verification
captcha_store.pop(ver_key, None)
return jsonify({'success': True})
return jsonify({'success': False, 'message': 'Captcha error'})
```
--------------------------------
### Generate Captcha with SpecCaptcha
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Initialize a captcha instance with dimensions and character count, then output to a file.
```python
from easy_captcha import SpecCaptcha
from io import BytesIO
# Three parameters: width, height, character count
captcha = SpecCaptcha(130, 48, 5)
# Get captcha text
code = captcha.text()
print(f"Captcha: {code}")
# Write to file
with open('captcha.png', 'wb') as f:
stream = BytesIO()
captcha.out(stream)
f.write(stream.getvalue())
```
--------------------------------
### Run All Types Demo Script
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/docs/EASYCAPTCHA-PYTHON-USAGE.md
Execute the comprehensive demo script that showcases all CAPTCHA types supported by easycaptcha-python. Generated images will be saved in the ./out/ directory.
```bash
python examples/all_types_demo.py
```
--------------------------------
### Captcha Configuration and Properties
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
This Python code shows how to instantiate and configure captcha objects, including setting dimensions and character length, and accessing their properties.
```python
from easy_captcha import SpecCaptcha, GifCaptcha, ArithmeticCaptcha
from io import BytesIO
# Constructor parameters: width, height, length
captcha = SpecCaptcha(width=200, height=60, length=6)
# Access properties
print(f"Width: {captcha.width}") # Output: Width: 200
print(f"Height: {captcha.height}") # Output: Height: 60
print(f"Length: {captcha.len}") # Output: Length: 6
# Modify properties after creation
captcha.width = 180
captcha.height = 50
captcha.len = 4
# For arithmetic captcha, len = number of operands
arith = ArithmeticCaptcha(130, 48)
arith.len = 3 # Three-number operation: a + b x c = ?
formula = arith.get_arithmetic_string()
print(f"Formula: {formula}") # Output: Formula: 5+3x2=?
# Generate after configuration
code = captcha.text()
stream = BytesIO()
captcha.out(stream)
```
--------------------------------
### Implement FastAPI Captcha Endpoints
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Demonstrates async captcha generation including PNG, GIF, and base64 formats. Uses an in-memory dictionary for state; replace with Redis for production environments.
```python
from fastapi import FastAPI, Response
from easy_captcha import SpecCaptcha, GifCaptcha, ArithmeticCaptcha
from io import BytesIO
app = FastAPI()
# In-memory store (use Redis in production)
captcha_store = {}
@app.get("/captcha")
async def get_captcha():
"""Return captcha as PNG image"""
cap = SpecCaptcha(130, 48, 5)
code = cap.text()
stream = BytesIO()
cap.out(stream)
return Response(content=stream.getvalue(), media_type="image/png")
@app.get("/captcha/gif")
async def get_gif_captcha():
"""Return animated GIF captcha"""
cap = GifCaptcha(130, 48, 5)
code = cap.text()
stream = BytesIO()
cap.out(stream)
return Response(content=stream.getvalue(), media_type="image/gif")
@app.get("/captcha/base64")
async def get_captcha_base64():
"""Return captcha as base64 with unique key for verification"""
import uuid
cap = SpecCaptcha(130, 48, 5)
code = cap.text().lower()
key = str(uuid.uuid4())
# Store for verification (use Redis with expiration in production)
captcha_store[key] = code
return {
"key": key,
"image": cap.to_base64()
}
@app.post("/verify")
async def verify_captcha(key: str, code: str):
"""Verify captcha code"""
stored_code = captcha_store.get(key)
if stored_code and code.lower() == stored_code:
del captcha_store[key]
return {"success": True}
return {"success": False, "message": "Invalid captcha"}
```
--------------------------------
### Output Captcha to BytesIO Stream
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Demonstrates how to capture the generated CAPTCHA image into a BytesIO stream, which can then be used for further processing or output.
```python
from io import BytesIO
stream = BytesIO()
captcha.out(stream)
```
--------------------------------
### Output Captcha to File
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/docs/EASYCAPTCHA-PYTHON-USAGE.md
Generate a CAPTCHA and save it directly to a file in binary write mode. This involves creating a BytesIO stream and writing its content to the specified file.
```python
from easy_captcha import SpecCaptcha
from io import BytesIO
captcha = SpecCaptcha(130, 48, 5)
# 输出到文件
with open('captcha.png', 'wb') as f:
stream = BytesIO()
captcha.out(stream)
f.write(stream.getvalue())
```
--------------------------------
### Implement Django Captcha Views
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Uses Django sessions to store captcha text for verification. Requires configuring URL patterns to map the provided view functions.
```python
from django.http import HttpResponse, JsonResponse
from django.views.decorators.http import require_POST
from easy_captcha import SpecCaptcha, ArithmeticCaptcha
from io import BytesIO
def captcha_view(request):
"""Generate PNG captcha and store text in session"""
cap = SpecCaptcha(130, 48, 5)
request.session['captcha'] = cap.text().lower()
stream = BytesIO()
cap.out(stream)
return HttpResponse(stream.getvalue(), content_type='image/png')
def arithmetic_captcha_view(request):
"""Generate arithmetic captcha"""
cap = ArithmeticCaptcha(130, 48, 2)
request.session['captcha'] = cap.text() # Store the result
stream = BytesIO()
cap.out(stream)
return HttpResponse(stream.getvalue(), content_type='image/png')
@require_POST
def verify_captcha(request):
"""Verify user-provided captcha code"""
import json
data = json.loads(request.body)
user_code = data.get('code', '').lower()
stored_code = request.session.get('captcha', '')
if user_code == stored_code:
del request.session['captcha']
return JsonResponse({'success': True})
return JsonResponse({'success': False, 'message': 'Invalid captcha'})
# urls.py
# from django.urls import path
# urlpatterns = [
# path('captcha/', captcha_view, name='captcha'),
# path('captcha/arithmetic/', arithmetic_captcha_view, name='captcha_arithmetic'),
# path('verify/', verify_captcha, name='verify_captcha'),
# ]
```
--------------------------------
### Configure Character Types for Captchas
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Demonstrates how to configure the character set for SpecCaptcha and GifCaptcha using predefined constants to generate captchas with specific character types like numbers only, letters only, or a mix of numbers and uppercase letters.
```python
from easy_captcha import (
SpecCaptcha, GifCaptcha,
TYPE_DEFAULT, # Numbers and letters (default)
TYPE_ONLY_NUMBER, # Numbers only (0-9)
TYPE_ONLY_CHAR, # Letters only (a-z, A-Z)
TYPE_ONLY_UPPER, # Uppercase letters only (A-Z)
TYPE_ONLY_LOWER, # Lowercase letters only (a-z)
TYPE_NUM_AND_UPPER # Numbers and uppercase letters
)
from io import BytesIO
# Numbers only captcha
captcha_num = SpecCaptcha(130, 48, 6)
captcha_num.char_type = TYPE_ONLY_NUMBER
code = captcha_num.text()
print(f"Numbers only: {code}") # Output: Numbers only: 847291
# Uppercase letters only
captcha_upper = SpecCaptcha(130, 48, 5)
captcha_upper.char_type = TYPE_ONLY_UPPER
code = captcha_upper.text()
print(f"Uppercase only: {code}") # Output: Uppercase only: MXKPW
# Numbers and uppercase (no ambiguous characters like 0/O, 1/I)
captcha_mixed = GifCaptcha(130, 48, 5)
captcha_mixed.char_type = TYPE_NUM_AND_UPPER
code = captcha_mixed.text()
print(f"Numbers + uppercase: {code}") # Output: Numbers + uppercase: 3KM9P
# Pure letters (both cases)
captcha_letters = SpecCaptcha(130, 48, 5)
captcha_letters.char_type = TYPE_ONLY_CHAR
code = captcha_letters.text()
print(f"Letters only: {code}") # Output: Letters only: aBcDe
```
--------------------------------
### Set Custom Font for Captcha
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Shows how to apply built-in fonts or system fonts to the CAPTCHA. Requires PIL.ImageFont for using system fonts.
```python
from easy_captcha import SpecCaptcha, FONT_1, FONT_2
captcha = SpecCaptcha(130, 48, 5)
# Set built-in font
captcha.set_font(FONT_1, size=32)
# You can also use system fonts (requires PIL.ImageFont support)
from PIL import ImageFont
captcha._font = ImageFont.truetype("arial.ttf", 32)
```
--------------------------------
### Integrate Captcha with FastAPI
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Return the captcha image as a FastAPI Response with the appropriate media type.
```python
from fastapi import FastAPI, Response
from easy_captcha import SpecCaptcha
from io import BytesIO
app = FastAPI()
@app.get("/captcha")
async def captcha():
cap = SpecCaptcha(130, 48, 5)
code = cap.text()
stream = BytesIO()
cap.out(stream)
return Response(content=stream.getvalue(), media_type="image/png")
```
--------------------------------
### Customize Captcha Fonts
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Shows how to customize the appearance of SpecCaptcha by setting built-in fonts with specific sizes or by using custom system fonts via PIL's ImageFont. Includes fallback to a built-in font if a custom font is not found.
```python
from easy_captcha import (
SpecCaptcha,
FONT_1, FONT_2, FONT_3, FONT_4, FONT_5,
FONT_6, FONT_7, FONT_8, FONT_9, FONT_10
)
from PIL import ImageFont
from io import BytesIO
# Use built-in font with custom size
captcha = SpecCaptcha(130, 48, 5)
captcha.set_font(FONT_1, size=32)
# Try different built-in fonts
captcha2 = SpecCaptcha(130, 48, 5)
captcha2.set_font(FONT_5, size=28)
captcha3 = SpecCaptcha(130, 48, 5)
captcha3.set_font(FONT_10, size=36)
# Use custom system font (requires PIL ImageFont)
captcha_custom = SpecCaptcha(130, 48, 5)
try:
captcha_custom._font = ImageFont.truetype("arial.ttf", 32)
except:
captcha_custom.set_font(FONT_1, size=32) # Fallback to built-in
# Output with custom font
with open('custom_font_captcha.png', 'wb') as f:
stream = BytesIO()
captcha.out(stream)
f.write(stream.getvalue())
```
--------------------------------
### Integrate Captcha with Flask
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Use Flask sessions to store and verify captcha text while serving the image as a response.
```python
from flask import Flask, session, make_response
from easy_captcha import SpecCaptcha
from io import BytesIO
app = Flask(__name__)
app.secret_key = 'your-secret-key'
@app.route('/captcha')
def captcha():
# Create captcha
cap = SpecCaptcha(130, 48, 5)
# Store captcha text in session
session['captcha'] = cap.text().lower()
# Output image
stream = BytesIO()
cap.out(stream)
response = make_response(stream.getvalue())
response.headers['Content-Type'] = 'image/png'
return response
@app.route('/verify/')
def verify(code):
# Get captcha from session
if code.lower() == session.get('captcha'):
return 'Verification successful'
return 'Verification failed'
```
--------------------------------
### Output Captcha as Base64 String
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/docs/EASYCAPTCHA-PYTHON-USAGE.md
Generate a CAPTCHA and encode it directly into a base64 string. An optional empty string argument to `to_base64()` can be used to omit the base64 header.
```python
from easy_captcha import SpecCaptcha
captcha = SpecCaptcha(130, 48, 5)
base64_str = captcha.to_base64()
# 如果不想要base64的头部data:image/png;base64,
base64_str = captcha.to_base64("") # 加一个空的参数即可
```
--------------------------------
### Generate Animated GIF Captcha with GifCaptcha
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Creates an animated GIF CAPTCHA. Use `text()` for verification, `out()` to save to a file stream, and `to_base64()` for base64 encoding.
```python
from easy_captcha import GifCaptcha
from io import BytesIO
# Create GIF captcha with width=130, height=48, 5 characters
captcha = GifCaptcha(130, 48, 5)
# Get the verification text
code = captcha.text()
print(f"Captcha text: {code}") # Output: Captcha text: B7mK2
# Output to file
with open('captcha.gif', 'wb') as f:
stream = BytesIO()
captcha.out(stream)
f.write(stream.getvalue())
# Output as base64 (note: GIF uses different MIME type)
base64_str = captcha.to_base64()
print(f"Base64: {base64_str[:50]}...") # Output: Base64: data:image/gif;base64,R0lGODlhg...
```
--------------------------------
### Integrate Captcha with Django
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Serve the captcha image via an HttpResponse and store the verification text in the Django session.
```python
from django.http import HttpResponse
from easy_captcha import SpecCaptcha
from io import BytesIO
def captcha(request):
cap = SpecCaptcha(130, 48, 5)
# Store captcha text in session
request.session['captcha'] = cap.text().lower()
# Output image
stream = BytesIO()
cap.out(stream)
return HttpResponse(stream.getvalue(), content_type='image/png')
```
--------------------------------
### Set Captcha Font
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/docs/EASYCAPTCHA-PYTHON-USAGE.md
Configure the font for CAPTCHAs using built-in fonts (FONT_1 to FONT_10) or system fonts via PIL.ImageFont. Ensure the font file exists and is accessible if using system fonts.
```python
from easy_captcha import SpecCaptcha, FONT_1, FONT_2
captcha = SpecCaptcha(130, 48, 5)
# 设置内置字体
captcha.set_font(FONT_1, size=32)
# 也可以使用系统字体(需要PIL.ImageFont支持)
from PIL import ImageFont
captcha._font = ImageFont.truetype("arial.ttf", 32)
```
--------------------------------
### Generate Different Captcha Types
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/docs/EASYCAPTCHA-PYTHON-USAGE.md
Instantiate and generate text or character arrays for various captcha types like SpecCaptcha, GifCaptcha, ChineseCaptcha, ChineseGifCaptcha, and ArithmeticCaptcha. For arithmetic captcha, note that `len` specifies the number of digits in the operation, and `text()` returns the result, not the formula.
```python
from easy_captcha import (
SpecCaptcha, GifCaptcha,
ChineseCaptcha,
ChineseGifCaptcha, ArithmeticCaptcha
)
# PNG类型
captcha = SpecCaptcha(130, 48, 5)
code = captcha.text() # 获取验证码文本
chars = captcha.text_char() # 获取验证码字符数组
# GIF类型
captcha = GifCaptcha(130, 48, 5)
# 中文类型
captcha = ChineseCaptcha(130, 48, 4)
# 中文GIF类型
captcha = ChineseGifCaptcha(130, 48, 4)
# 算术类型
captcha = ArithmeticCaptcha(130, 48, 2)
captcha.len = 3 # 几位数运算,默认是两位
formula = captcha.get_arithmetic_string() # 获取运算公式:3+2=?
result = captcha.text() # 获取运算结果:5
# 输出验证码
from io import BytesIO
stream = BytesIO()
captcha.out(stream)
```
--------------------------------
### Generate Animated Chinese Character Captcha
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
Creates an animated Chinese character captcha, outputs its verification text, saves it as a GIF file, and provides a base64 encoded string representation.
```python
from easy_captcha import ChineseGifCaptcha
from io import BytesIO
# Create animated Chinese captcha
captcha = ChineseGifCaptcha(130, 48, 4)
# Get verification text
code = captcha.text()
print(f"Captcha text: {code}")
# Output as animated GIF file
with open('chinese_captcha.gif', 'wb') as f:
stream = BytesIO()
captcha.out(stream)
f.write(stream.getvalue())
# Output as base64 for API responses
base64_str = captcha.to_base64()
print(f"Base64 (GIF): {base64_str[:50]}...")
```
--------------------------------
### Flask Login Endpoint with Captcha Verification
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
This Flask route handles user login, verifying the provided captcha code against the stored code using a verification key. It removes the used captcha from storage before proceeding with authentication.
```python
@app.route('/api/login', methods=['POST'])
def login():
"""Login with captcha verification"""
data = request.json
ver_key = data.get('verKey')
ver_code = data.get('verCode', '').lower()
username = data.get('username')
password = data.get('password')
# Verify captcha first
if ver_code != captcha_store.get(ver_key):
return jsonify({'success': False, 'message': 'Invalid captcha'})
# Remove used captcha
captcha_store.pop(ver_key, None)
# Proceed with authentication
# ... your auth logic here ...
return jsonify({'success': True, 'message': 'Login successful'})
```
--------------------------------
### Flask API Endpoints for Captcha Generation
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
These Flask routes handle the generation of PNG and GIF captchas, storing the verification code in memory and returning a verification key and base64 encoded image.
```python
captcha_store = {}
@app.route('/api/captcha')
def get_captcha():
"""Return captcha as base64 with verification key"""
cap = SpecCaptcha(130, 48, 5)
code = cap.text().lower()
key = str(uuid.uuid4())
captcha_store[key] = code
return jsonify({
'key': key,
'image': cap.to_base64() # data:image/png;base64,...
})
```
```python
@app.route('/api/captcha/gif')
def get_gif_captcha():
"""Return GIF captcha as base64"""
cap = GifCaptcha(130, 48, 5)
code = cap.text().lower()
key = str(uuid.uuid4())
captcha_store[key] = code
return jsonify({
'key': key,
'image': cap.to_base64() # data:image/gif;base64,...
})
```
--------------------------------
### Frontend JavaScript for Captcha Integration
Source: https://context7.com/savlgoodman/easycaptcha-python/llms.txt
This JavaScript code demonstrates how to integrate with the Flask captcha API. It includes functions to refresh the captcha image and send login credentials with verification.
```html
```
```javascript
let verKey = '';
async function refreshCaptcha() {
const response = await fetch('/api/captcha');
const data = await response.json();
verKey = data.key;
document.getElementById('captchaImg').src = data.image;
}
async function login() {
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
verKey: verKey,
verCode: document.getElementById('captchaInput').value,
username: 'admin',
password: 'password123'
})
});
const result = await response.json();
console.log(result);
}
// Load captcha on page load
refreshCaptcha();
```
--------------------------------
### Display Captcha in HTML
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/README.md
Embed the captcha image in an HTML page using the route defined in the backend.
```html
```
--------------------------------
### Set Captcha Character Type
Source: https://github.com/savlgoodman/easycaptcha-python/blob/master/docs/EASYCAPTCHA-PYTHON-USAGE.md
Customize the character set for SpecCaptcha and GifCaptcha using predefined types like TYPE_ONLY_NUMBER, TYPE_ONLY_CHAR, etc. This setting only affects SpecCaptcha and GifCaptcha.
```python
from easy_captcha import SpecCaptcha, TYPE_ONLY_NUMBER
captcha = SpecCaptcha(130, 48, 5)
captcha.char_type = TYPE_ONLY_NUMBER
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.