You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

131 lines
3.0 KiB
Python

from pathlib import Path
from flask import Flask, redirect, render_template, url_for
from flask_login import (
LoginManager,
current_user,
login_required,
login_user,
logout_user,
)
from forms import IdeaForm, LoginForm, RegistrationForm
from models import Idea, User, db
BASE_DIR = Path(__file__).resolve(strict=True).parent
app = Flask(__name__)
app.config["SECRET_KEY"] = "hard to guess string"
app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{BASE_DIR}/geistesblitze.sqlite"
db.init_app(app)
login_manager = LoginManager(app)
login_manager.session_protection = "strong"
login_manager.login_view = "login"
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@app.cli.command()
def create_all():
"""Create all the tables"""
db.create_all()
@app.route("/")
def index():
if current_user.is_authenticated:
ideas = Idea.query.filter_by(user=current_user).all()
else:
ideas = []
return render_template("index.html", ideas=ideas)
@app.route("/register", methods=["GET", "POST"])
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, password=form.password.data)
db.session.add(user)
db.session.commit()
login_user(user, True)
return redirect(url_for("index"))
return render_template("partials/register.html", form=form)
@app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is not None and user.verify_password(form.password.data):
login_user(user, True)
return redirect(url_for("index"))
return render_template("partials/login.html", form=form)
@app.route("/logout")
def logout():
logout_user()
return redirect(url_for("index"))
@app.route("/add_idea", methods=["GET", "POST"])
@login_required
def add_idea():
form = IdeaForm()
if form.validate_on_submit():
idea = Idea(name=form.name.data, description=form.description.data, user=current_user)
db.session.add(idea)
db.session.commit()
return redirect(url_for("index"))
return render_template("partials/add_idea.html", form=form)
@app.route("/edit_idea/<int:id_>", methods=["GET", "POST"])
@login_required
def edit_idea(id_):
idea = Idea.query.filter_by(id=id_).first()
form = IdeaForm()
if form.validate_on_submit():
idea.name = form.name.data
idea.description = form.description.data
db.session.add(idea)
db.session.commit()
return redirect(url_for("index"))
return render_template("partials/edit_idea.html", idea=idea, form=form)
@app.route("/ideas/<int:id_>", methods=["DELETE"])
@login_required
def delete_idea(id_):
idea = Idea.query.filter_by(id=id_).first()
db.session.delete(idea)
db.session.commit()
return "", 200