91 lines
3 KiB
Python
91 lines
3 KiB
Python
from flask import Flask, current_app
|
|
from flask_sqlalchemy import SQLAlchemy
|
|
from flask_login import LoginManager
|
|
from config import Config
|
|
import os
|
|
from datetime import datetime
|
|
import sqlite3
|
|
|
|
# Initialize extensions
|
|
db = SQLAlchemy()
|
|
login_manager = LoginManager()
|
|
login_manager.login_view = 'auth.login'
|
|
login_manager.login_message_category = 'info'
|
|
|
|
def initialize_database(app):
|
|
"""Create database tables if they don't exist"""
|
|
with app.app_context():
|
|
try:
|
|
# Create all tables
|
|
db.create_all()
|
|
app.logger.info("Database tables created successfully")
|
|
except Exception as e:
|
|
app.logger.error(f"Error creating database tables: {str(e)}")
|
|
|
|
def run_migrations(app):
|
|
"""Apply any necessary database migrations"""
|
|
db_path = app.config['SQLALCHEMY_DATABASE_URI'].replace('sqlite:///', '')
|
|
|
|
if not os.path.exists(db_path):
|
|
app.logger.info(f"Database file does not exist: {db_path}")
|
|
return
|
|
|
|
try:
|
|
conn = sqlite3.connect(db_path)
|
|
cursor = conn.cursor()
|
|
|
|
# Check if storage_name column exists in file table
|
|
cursor.execute("PRAGMA table_info(file)")
|
|
columns = [column[1] for column in cursor.fetchall()]
|
|
|
|
if 'storage_name' not in columns:
|
|
app.logger.info("Adding storage_name column to file table")
|
|
cursor.execute("ALTER TABLE file ADD COLUMN storage_name TEXT")
|
|
|
|
# Update existing records to use filename as storage_name
|
|
cursor.execute("UPDATE file SET storage_name = name WHERE storage_name IS NULL AND is_folder = 0")
|
|
conn.commit()
|
|
|
|
conn.close()
|
|
app.logger.info("Database migrations completed successfully")
|
|
except sqlite3.OperationalError as e:
|
|
if "no such table: file" in str(e):
|
|
app.logger.info("File table doesn't exist yet, will be created with db.create_all()")
|
|
else:
|
|
app.logger.error(f"Error during migration: {str(e)}")
|
|
except Exception as e:
|
|
app.logger.error(f"Error during migration: {str(e)}")
|
|
|
|
def create_app(config_class=Config):
|
|
app = Flask(__name__)
|
|
app.config.from_object(config_class)
|
|
|
|
# Initialize extensions
|
|
db.init_app(app)
|
|
login_manager.init_app(app)
|
|
|
|
# Initialize the upload folder
|
|
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
|
|
|
|
# Auto initialize database if it doesn't exist
|
|
with app.app_context():
|
|
initialize_database(app)
|
|
run_migrations(app)
|
|
|
|
# Register blueprints
|
|
from app.routes.auth import auth_bp
|
|
from app.routes.files import files_bp
|
|
from app.routes.dashboard import dashboard_bp
|
|
|
|
app.register_blueprint(auth_bp)
|
|
app.register_blueprint(files_bp)
|
|
app.register_blueprint(dashboard_bp)
|
|
|
|
# Add context processor for template variables
|
|
@app.context_processor
|
|
def inject_now():
|
|
return {'now': datetime.now()}
|
|
|
|
return app
|
|
|
|
from app import models
|