This commit is contained in:
pika 2025-03-23 00:40:29 +01:00
parent eb93961967
commit ea3e92b8b7
10 changed files with 773 additions and 167 deletions

View file

@ -1,16 +1,61 @@
from flask import Flask
from flask import Flask, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import Config
from datetime import datetime
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)
@ -20,7 +65,7 @@ def create_app(config_class=Config):
login_manager.init_app(app)
# Initialize the upload folder
Config.init_app(app)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Auto initialize database if it doesn't exist
with app.app_context():
@ -28,7 +73,10 @@ def create_app(config_class=Config):
run_migrations(app)
# Register blueprints
from app.routes import auth_bp, files_bp, dashboard_bp
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)
@ -40,51 +88,4 @@ def create_app(config_class=Config):
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