90 lines
2.8 KiB
Python
90 lines
2.8 KiB
Python
from flask import Flask
|
|
from flask_sqlalchemy import SQLAlchemy
|
|
from flask_login import LoginManager
|
|
from config import Config
|
|
from datetime import datetime
|
|
import os
|
|
import sqlite3
|
|
|
|
db = SQLAlchemy()
|
|
login_manager = LoginManager()
|
|
login_manager.login_view = 'auth.login'
|
|
login_manager.login_message_category = 'info'
|
|
|
|
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
|
|
Config.init_app(app)
|
|
|
|
# Auto initialize database if it doesn't exist
|
|
with app.app_context():
|
|
initialize_database(app)
|
|
run_migrations(app)
|
|
|
|
# Register blueprints
|
|
from app.routes import auth_bp, files_bp, 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
|
|
|
|
def initialize_database(app):
|
|
"""Create database tables if they don't exist."""
|
|
db_path = app.config['SQLALCHEMY_DATABASE_URI'].replace('sqlite:///', '')
|
|
|
|
# Check if database file exists
|
|
if not os.path.exists(db_path):
|
|
print("Database does not exist. Creating tables...")
|
|
db.create_all()
|
|
|
|
# Import models here to avoid circular imports
|
|
from app.models import User
|
|
|
|
# Create admin user if it doesn't exist
|
|
admin = User.query.filter_by(username='admin').first()
|
|
if not admin:
|
|
admin = User(username='admin')
|
|
admin.set_password('admin') # Change this in production
|
|
db.session.add(admin)
|
|
db.session.commit()
|
|
print("Admin user created.")
|
|
|
|
def run_migrations(app):
|
|
"""Run any needed database migrations."""
|
|
db_path = app.config['SQLALCHEMY_DATABASE_URI'].replace('sqlite:///', '')
|
|
conn = sqlite3.connect(db_path)
|
|
cursor = conn.cursor()
|
|
|
|
try:
|
|
# Check for missing columns in File table
|
|
cursor.execute("PRAGMA table_info(file)")
|
|
columns = [column[1] for column in cursor.fetchall()]
|
|
|
|
# Add storage_name column if missing
|
|
if 'storage_name' not in columns:
|
|
print("Running migration: Adding storage_name column to file table...")
|
|
cursor.execute("ALTER TABLE file ADD COLUMN storage_name TEXT")
|
|
|
|
# Update existing files to use name as storage_name
|
|
cursor.execute("UPDATE file SET storage_name = name WHERE is_folder = 0")
|
|
|
|
conn.commit()
|
|
print("Migration completed successfully!")
|
|
except Exception as e:
|
|
print(f"Migration error: {e}")
|
|
finally:
|
|
conn.close()
|
|
|
|
from app import models
|