102 lines
2.4 KiB
Python
102 lines
2.4 KiB
Python
# app.py
|
|
|
|
from flask import Flask, request, render_template, jsonify, redirect, url_for
|
|
from sqlalchemy import create_engine, func
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
from config.config import config
|
|
from models.album import Base, Album
|
|
|
|
app = Flask(__name__)
|
|
engine = create_engine(config['DB_URL'])
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@app.route('/')
|
|
def index():
|
|
db = next(get_db())
|
|
albums = db.query(Album).all()
|
|
return render_template('index.html', albums=albums)
|
|
|
|
|
|
@app.route('/admin', methods=['GET'])
|
|
def admin_get():
|
|
db = next(get_db())
|
|
albums = db.query(Album).all()
|
|
return render_template('admin.html', albums=albums)
|
|
|
|
|
|
@app.route('/admin', methods=['POST'])
|
|
def admin_post():
|
|
action = request.form.get('action')
|
|
album_id = request.form.get('album_id')
|
|
|
|
if not action:
|
|
return redirect('/admin')
|
|
|
|
try:
|
|
if album_id is not None:
|
|
album_id = int(album_id)
|
|
except ValueError:
|
|
return redirect('/admin')
|
|
|
|
db = next(get_db())
|
|
|
|
if action == 'edit':
|
|
title = request.form.get('title')
|
|
artist = request.form.get('artist')
|
|
year = request.form.get('year')
|
|
|
|
if not title or not artist or not year:
|
|
return redirect('/admin')
|
|
|
|
album = db.query(Album).filter(Album.id == album_id).first()
|
|
if album:
|
|
album.title = title
|
|
album.artist = artist
|
|
album.year = int(year)
|
|
db.commit()
|
|
return redirect('/admin')
|
|
else:
|
|
return redirect('/admin')
|
|
|
|
|
|
|
|
elif action == 'delete':
|
|
album = db.query(Album).filter(Album.id == album_id).first()
|
|
if album:
|
|
db.delete(album)
|
|
db.commit()
|
|
return redirect('/admin')
|
|
else:
|
|
return redirect('/admin')
|
|
|
|
elif action == 'add_album':
|
|
title = request.form.get('title')
|
|
artist = request.form.get('artist')
|
|
year = request.form.get('year')
|
|
|
|
if not title or not artist or not year:
|
|
return redirect('/admin')
|
|
|
|
new_album = Album(title=title, artist=artist, year=int(year))
|
|
db.add(new_album)
|
|
db.commit()
|
|
return redirect('/admin')
|
|
|
|
else:
|
|
return redirect('/admin')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True)
|