flask-base/app.py

111 lines
3.2 KiB
Python

from flask import Flask, render_template, redirect, url_for, request
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user
from werkzeug.security import generate_password_hash, check_password_hash
import os
app = Flask(__name__)
# Ensure instance directory exists
# Ensure instance and database directories exist
app.config["SECRET_KEY"] = os.environ.get(
"FLASK_SECRET_KEY", "your-secret-key-here" # Fallback for development only
)
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_DATABASE_URI", "sqlite:///instance/database.db") # Read from environment
# Ensure database directory exists AFTER config is set
with app.app_context():
db_path = app.config["SQLALCHEMY_DATABASE_URI"].replace("sqlite:///", "")
try:
os.makedirs(os.path.dirname(db_path), exist_ok=True, mode=0o755)
print(f"Ensured database directory exists at {os.path.dirname(db_path)}")
except Exception as e:
print(f"Error creating database directory: {str(e)}")
raise
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
# Initialize database CLI command
@app.cli.command("init-db")
def init_db():
import os
db_path = app.config["SQLALCHEMY_DATABASE_URI"].replace("sqlite:///", "")
os.makedirs(os.path.dirname(db_path), exist_ok=True, mode=0o755)
with app.app_context():
db.create_all()
print(f"Database created at {db_path}")
login_manager = LoginManager(app)
login_manager.login_view = "login"
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100))
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.route("/")
def home():
return redirect(url_for("login"))
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
email = request.form.get("email")
password = request.form.get("password")
user = User.query.filter_by(email=email).first()
if user and check_password_hash(user.password, password):
login_user(user)
return redirect(url_for("dashboard"))
return "Invalid credentials"
return render_template("login.html")
@app.route("/register", methods=["GET", "POST"])
def register():
if request.method == "POST":
email = request.form.get("email")
password = request.form.get("password")
confirm_password = request.form.get("confirm_password")
if password != confirm_password:
return "Passwords do not match"
if User.query.filter_by(email=email).first():
return "Email already registered"
password = generate_password_hash(password)
new_user = User(email=email, password=password)
db.session.add(new_user)
db.session.commit()
return redirect(url_for("login"))
return render_template("register.html")
@app.route("/dashboard")
@login_required
def dashboard():
return render_template("dashboard.html")
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for("login"))