|
| 1 | +from flask import Flask, jsonify |
| 2 | +from controllers.payment_controller import payment_bp |
| 3 | +from controllers.webhook_controller import webhook_bp |
| 4 | +from logging_config import setup_logging |
| 5 | +from werkzeug.exceptions import HTTPException |
| 6 | +import os |
| 7 | + |
| 8 | +def create_app(config_name='development'): |
| 9 | + """Create and configure the Flask application.""" |
| 10 | + app = Flask(__name__) |
| 11 | + |
| 12 | + # Load configuration from environment variables or a config file |
| 13 | + app.config.from_object(f'config.{config_name.capitalize()}Config') |
| 14 | + |
| 15 | + # Register blueprints |
| 16 | + app.register_blueprint(payment_bp) |
| 17 | + app.register_blueprint(webhook_bp) |
| 18 | + |
| 19 | + # Middleware for security headers |
| 20 | + @app.after_request |
| 21 | + def add_security_headers(response): |
| 22 | + response.headers['X-Content-Type-Options'] = 'nosniff' |
| 23 | + response.headers['X-Frame-Options'] = 'DENY' |
| 24 | + response.headers['X-XSS-Protection'] = '1; mode=block' |
| 25 | + return response |
| 26 | + |
| 27 | + return app |
| 28 | + |
| 29 | +def handle_error(e): |
| 30 | + """Custom error handler for exceptions.""" |
| 31 | + if isinstance(e, HTTPException): |
| 32 | + response = e.get_response() |
| 33 | + response.data = jsonify({"error": e.description, "status": "error"}).get_data() |
| 34 | + response.content_type = "application/json" |
| 35 | + return response |
| 36 | + else: |
| 37 | + response = { |
| 38 | + "error": str(e), |
| 39 | + "status": "error" |
| 40 | + } |
| 41 | + return jsonify(response), 500 |
| 42 | + |
| 43 | +if __name__ == '__main__': |
| 44 | + # Set up logging |
| 45 | + setup_logging() |
| 46 | + |
| 47 | + # Create the Flask app |
| 48 | + app = create_app(os.getenv('FLASK_ENV', 'development')) |
| 49 | + |
| 50 | + # Register error handler |
| 51 | + app.register_error_handler(Exception, handle_error) |
| 52 | + |
| 53 | + # Run the application |
| 54 | + app.run(host='0.0.0.0', port=int(os.getenv('PORT', 5000)), debug=app.config['DEBUG']) |
0 commit comments