File size: 5,585 Bytes
2a9b5c4
d488241
f788a29
2a9b5c4
d488241
f788a29
d488241
092e58d
7295b0b
 
092e58d
d488241
7295b0b
 
 
 
 
 
 
 
092e58d
d488241
f788a29
d488241
092e58d
f788a29
092e58d
d488241
179bfbc
 
 
 
 
 
f788a29
7295b0b
 
092e58d
d488241
7295b0b
092e58d
d488241
f788a29
 
092e58d
 
7295b0b
092e58d
d488241
092e58d
d488241
7295b0b
d488241
f788a29
7295b0b
 
d488241
092e58d
 
7295b0b
d488241
 
092e58d
7295b0b
 
 
f788a29
 
 
 
 
 
 
7295b0b
 
f788a29
 
 
7295b0b
 
 
c2c6bd3
 
 
 
 
 
7295b0b
 
 
c2c6bd3
 
7295b0b
c2c6bd3
 
2a9b5c4
c2c6bd3
7295b0b
c2c6bd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4883166
c2c6bd3
 
 
 
 
 
 
 
 
 
 
 
7295b0b
f788a29
 
 
 
 
 
 
 
7295b0b
 
 
2a9b5c4
 
 
 
 
 
 
 
d488241
7295b0b
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
from flask import Flask, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager, current_user
from celery import Celery
from config import Config
import redis
import os
import logging
import sys
from pathlib import Path

# Configure logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger(__name__)

# Initialize extensions
db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()
login.login_view = 'auth.login'
celery = Celery(__name__, broker=Config.CELERY_BROKER_URL)
cache = None  # Initialize later when app context is available

# Set up user loader for Flask-Login
@login.user_loader
def load_user(user_id):
    from .models import User
    return User.query.get(int(user_id))

def create_app(config_class=Config):
    logger.info("Starting application initialization...")
    
    # Create the Flask app
    app = Flask(__name__)
    logger.info("Flask app created")
    
    # Load configuration
    logger.info(f"Loading configuration from {config_class}...")
    app.config.from_object(config_class)
    
    # Ensure instance path exists
    logger.info(f"Ensuring instance path exists: {app.config['INSTANCE_PATH']}")
    Path(app.config['INSTANCE_PATH']).mkdir(parents=True, exist_ok=True)
    app.instance_path = app.config['INSTANCE_PATH']
    
    # Initialize extensions
    logger.info("Initializing SQLAlchemy...")
    db.init_app(app)
    migrate.init_app(app, db)
    
    logger.info("Initializing LoginManager...")
    login.init_app(app)
    
    # Configure Celery
    logger.info("Configuring Celery...")
    celery.conf.update(app.config)
    
    # Initialize Redis cache
    try:
        logger.info(f"Initializing Redis cache with URL: {app.config['CELERY_BROKER_URL']}")
        global cache
        # Only try to connect to Redis if the URL starts with 'redis://'
        if app.config['CELERY_BROKER_URL'].startswith('redis://'):
            cache = redis.Redis.from_url(app.config['CELERY_BROKER_URL'])
            logger.info("Redis cache initialized successfully")
        else:
            logger.info("Not using Redis cache as broker URL is not Redis")
            cache = None
    except Exception as e:
        logger.error(f"Error initializing Redis cache: {e}")
        # Continue without Redis
        cache = None
        logger.info("Continuing without Redis cache")
    
    # Register test blueprint first (this should always work)
    logger.info("Registering test blueprint...")
    try:
        from .routes.test import test_bp
        app.register_blueprint(test_bp)
        logger.info("Test blueprint registered successfully")
    except Exception as e:
        logger.error(f"Error registering test blueprint: {e}")
    
    # Register other blueprints
    logger.info("Registering other blueprints...")
    
    # Try to register each blueprint individually
    try:
        logger.info("Importing and registering dashboard blueprint...")
        from .routes.dashboard import dashboard_bp
        app.register_blueprint(dashboard_bp, url_prefix='/dashboard')
        logger.info("Dashboard blueprint registered successfully")
    except Exception as e:
        logger.error(f"Error registering dashboard blueprint: {e}")
    
    try:
        logger.info("Importing and registering API blueprint...")
        from .routes.api import api_bp
        app.register_blueprint(api_bp)
        logger.info("API blueprint registered successfully")
    except Exception as e:
        logger.error(f"Error registering API blueprint: {e}")
    
    try:
        logger.info("Importing and registering compliance blueprint...")
        from .routes.compliance import compliance_bp
        app.register_blueprint(compliance_bp)
        logger.info("Compliance blueprint registered successfully")
    except Exception as e:
        logger.error(f"Error registering compliance blueprint: {e}")
    
    try:
        logger.info("Importing and registering Google Ads blueprint...")
        from .routes.google_ads import google_ads_bp
        app.register_blueprint(google_ads_bp)
        logger.info("Google Ads blueprint registered successfully")
    except Exception as e:
        logger.error(f"Error registering Google Ads blueprint: {e}")
    
    try:
        logger.info("Importing and registering auth blueprint...")
        from .routes.auth import auth_bp
        app.register_blueprint(auth_bp)
        logger.info("Auth blueprint registered successfully")
    except Exception as e:
        logger.error(f"Error registering auth blueprint: {e}")
    
    try:
        logger.info("Importing and registering Facebook Ads blueprint...")
        from .routes.facebook_ads import facebook_ads_bp
        app.register_blueprint(facebook_ads_bp)
        logger.info("Facebook Ads blueprint registered successfully")
    except Exception as e:
        logger.error(f"Error registering Facebook Ads blueprint: {e}")
    
    # Add a simple route directly to the app
    @app.route('/')
    def index():
        if current_user.is_authenticated:
            try:
                return redirect(url_for('dashboard.index'))
            except:
                # Fallback to facebook_ads if dashboard is not available
                return redirect(url_for('facebook_ads.index'))
        else:
            return redirect(url_for('auth.login'))
    
    logger.info("Application initialization complete")
    return app