63 lines
1.9 KiB
Python
63 lines
1.9 KiB
Python
from flask import Flask, render_template, request, redirect, url_for
|
|
from flask_sqlalchemy import SQLAlchemy
|
|
import os
|
|
|
|
basedir = os.path.abspath(os.path.dirname(__file__))
|
|
|
|
app = Flask(__name__)
|
|
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'buecher.sql')
|
|
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
|
db = SQLAlchemy(app)
|
|
|
|
# Datenbankmodell für ein Buch
|
|
class Buch(db.Model):
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
titel = db.Column(db.String(80), nullable=False)
|
|
autor = db.Column(db.String(80), nullable=False)
|
|
jahr = db.Column(db.Integer)
|
|
|
|
def __repr__(self):
|
|
return f'<Buch {self.titel}>'
|
|
|
|
with app.app_context():
|
|
db.create_all()
|
|
|
|
# Routen für die Anwendung
|
|
@app.route('/')
|
|
def index():
|
|
buecher = Buch.query.all()
|
|
return render_template('index.html', buecher=buecher)
|
|
|
|
@app.route('/hinzufuegen', methods=['GET', 'POST'])
|
|
def hinzufuegen():
|
|
if request.method == 'POST':
|
|
titel = request.form['titel']
|
|
autor = request.form['autor']
|
|
jahr = request.form.get('jahr', None) # Jahr kann optional sein
|
|
neues_buch = Buch(titel=titel, autor=autor, jahr=jahr)
|
|
db.session.add(neues_buch)
|
|
db.session.commit()
|
|
return redirect(url_for('index'))
|
|
return render_template('hinzufuegen.html')
|
|
|
|
@app.route('/bearbeiten/<int:id>', methods=['GET', 'POST'])
|
|
def bearbeiten(id):
|
|
buch = Buch.query.get_or_404(id)
|
|
if request.method == 'POST':
|
|
buch.titel = request.form['titel']
|
|
buch.autor = request.form['autor']
|
|
buch.jahr = request.form.get('jahr', None)
|
|
db.session.commit()
|
|
return redirect(url_for('index'))
|
|
return render_template('bearbeiten.html', buch=buch)
|
|
|
|
@app.route('/loeschen/<int:id>')
|
|
def loeschen(id):
|
|
buch = Buch.query.get_or_404(id)
|
|
db.session.delete(buch)
|
|
db.session.commit()
|
|
return redirect(url_for('index'))
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True)
|