1. import time
  2. from flask import Flask, request, jsonify
  3. app = Flask(__name__)
  4. REQUEST_LIMIT = 5 # Number of requests allowed
  5. TIME_WINDOW = 60 # Time window in seconds
  6. request_counts = {} # Dictionary to store request counts per IP address
  7. def is_rate_limited(ip_address):
  8. """Checks if the IP address is rate-limited."""
  9. if ip_address not in request_counts:
  10. request_counts[ip_address] = 0
  11. if request_counts[ip_address] >= REQUEST_LIMIT:
  12. return True
  13. request_counts[ip_address] += 1
  14. return False
  15. @app.route('/form', methods=['POST'])
  16. def submit_form():
  17. """Handles form submissions with rate limiting."""
  18. ip_address = request.remote_addr
  19. if is_rate_limited(ip_address):
  20. return jsonify({"error": "Rate limit exceeded. Please try again later."}), 429 # 429 Too Many Requests
  21. try:
  22. # Process the form data
  23. data = request.get_json()
  24. # Simulate a potential failure
  25. if 'error' in data and data['error'] == 'simulated_error':
  26. return jsonify({"error": "Simulated form submission error."}), 500
  27. # ... Your form processing logic here ...
  28. print("Form submitted successfully.")
  29. return jsonify({"message": "Form submitted successfully."}), 200
  30. except Exception as e:
  31. # Handle form processing errors
  32. print(f"Form processing error: {e}")
  33. return jsonify({"error": "Internal server error."}), 500
  34. finally:
  35. # Reset request count after successful processing
  36. if ip_address in request_counts:
  37. request_counts[ip_address] = 0
  38. if __name__ == '__main__':
  39. app.run(debug=True)

Add your comment