File size: 1,755 Bytes
d488241 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | from flask import Blueprint, jsonify, request
from flask_login import login_required
from ..models import Ad
from ..services.ai_processor import AIPipeline
from ..utils.validators import validate_request_json
from ..utils.decorators import cache_response
import logging
logger = logging.getLogger(__name__)
# Try to import ratelimit, but provide a fallback if it's not available
try:
from ratelimit import limits, RateLimitException
RATELIMIT_AVAILABLE = True
logger.info("Rate limiting is enabled")
except ImportError:
logger.warning("ratelimit package not found. Rate limiting is disabled.")
RATELIMIT_AVAILABLE = False
# Define fallback decorator and exception
def limits(calls, period):
def decorator(f):
return f
return decorator
class RateLimitException(Exception):
pass
api_bp = Blueprint('api', __name__)
ONE_MINUTE = 60
MAX_REQUESTS_PER_MINUTE = 30
@api_bp.route('/ads', methods=['GET'])
@login_required
def get_ads():
ads = Ad.query.all()
return jsonify([{
'id': ad.id,
'content': ad.content,
'sentiment': ad.sentiment
} for ad in ads])
@api_bp.route('/analyze', methods=['POST'])
@login_required
@limits(calls=MAX_REQUESTS_PER_MINUTE, period=ONE_MINUTE)
def analyze_ad():
validation_error = validate_request_json(['text'])
if validation_error:
return validation_error
try:
data = request.json
ad_text = data['text']
ai = AIPipeline()
result = ai.process_ad(ad_text)
return jsonify(result)
except RateLimitException:
return jsonify({"error": "Rate limit exceeded"}), 429
except Exception as e:
return jsonify({"error": str(e)}), 500 |