from flask import Flask, request, jsonify import time
app = Flask(__name__)
# 存储被封禁的IP和封禁时间 banned_ips = {}
@app.before_request defcheck_ip(): client_ip = request.remote_addr # 检查IP是否被封禁 if client_ip in banned_ips: ban_time, duration = banned_ips[client_ip] if time.time() < ban_time + duration: return jsonify({"error": " Your IP is temporarily banned."}), 403 else: del banned_ips[client_ip] # 解除封禁
# 假设检查频率,只是在演示 if is_suspicious_activity(client_ip): banned_ips[client_ip] = (time.time(), 300) # 封禁5分钟 return jsonify({"error": "Too many requests, you are temporarily banned."}), 403
# 连接数据库 conn = sqlite3.connect('banned_ips.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS banned_ips (ip TEXT PRIMARY KEY, banned_time REAL)''') conn.commit()
defcheck_permanent_ban(ip): c.execute("SELECT * FROM banned_ips WHERE ip=?", (ip,)) return c.fetchone() isnotNone
defban_permanently(ip): c.execute("INSERT OR REPLACE INTO banned_ips (ip, banned_time) VALUES (?, ?)", (ip, time.time())) conn.commit()
@app.before_request defcheck_ip(): client_ip = request.remote_addr # 检查永久封禁 if check_permanent_ban(client_ip): return jsonify({"error": "Your IP is permanently banned."}), 403
if client_ip in banned_ips: ban_time, duration = banned_ips[client_ip] if time.time() < ban_time + duration: return jsonify({"error": "Your IP is temporarily banned."}), 403 else: del banned_ips[client_ip]
if is_suspicious_activity(client_ip): # 如果是恶意行为,考虑永久封禁 ban_permanently(client_ip) return jsonify({"error": "Your IP has been permanently banned due to malicious activity."}), 403