63 lines
1.6 KiB
Python
63 lines
1.6 KiB
Python
|
|
# app.py
|
||
|
|
|
||
|
|
from flask import Flask, request, render_template, redirect, url_for
|
||
|
|
from sqlalchemy import create_engine, func
|
||
|
|
from sqlalchemy.orm import sessionmaker
|
||
|
|
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', 'POST'])
|
||
|
|
def admin():
|
||
|
|
if request.method == 'POST':
|
||
|
|
action = request.form['action']
|
||
|
|
album_id = int(request.form['album_id'])
|
||
|
|
|
||
|
|
db = next(get_db())
|
||
|
|
|
||
|
|
if action == 'edit':
|
||
|
|
title = request.form['title']
|
||
|
|
artist = request.form['artist']
|
||
|
|
year = int(request.form['year'])
|
||
|
|
|
||
|
|
album = db.query(Album).filter(Album.id == album_id).first()
|
||
|
|
if album:
|
||
|
|
album.title = title
|
||
|
|
album.artist = artist
|
||
|
|
album.year = year
|
||
|
|
db.commit()
|
||
|
|
elif action == 'delete':
|
||
|
|
album = db.query(Album).filter(Album.id == album_id).first()
|
||
|
|
if album:
|
||
|
|
db.delete(album)
|
||
|
|
db.commit()
|
||
|
|
|
||
|
|
return redirect(url_for('admin'))
|
||
|
|
|
||
|
|
db = next(get_db())
|
||
|
|
albums = db.query(Album).all()
|
||
|
|
return render_template('admin.html', albums=albums)
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
app.run(debug=True)
|