Files
Flask_CRUD_example/app.py
2025-11-27 16:25:46 +01:00

93 lines
3.1 KiB
Python

from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import select
from sqlalchemy.orm import Mapped, mapped_column
from typing import Optional
from pathlib import Path
app = Flask(__name__)
app.config.update(
SQLALCHEMY_DATABASE_URI='sqlite:///' + str(Path(__file__).with_name('database.db')),
SQLALCHEMY_TRACK_MODIFICATIONS=False,
)
db = SQLAlchemy(app)
class Contact(db.Model):
__tablename__ = 'contacts'
id: Mapped[int] = mapped_column(db.Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(db.String(255), nullable=False)
email: Mapped[Optional[str]] = mapped_column(db.String(255), nullable=True)
phone: Mapped[Optional[str]] = mapped_column(db.String(50), nullable=True)
def __repr__(self) -> str:
return f"<Contact id={self.id} name={self.name!r}>"
# tworzymy tabelę przy starcie (w projekcie produkcyjnym użyj migracji)
with app.app_context():
db.create_all()
@app.get('/')
def index():
rows = db.session.execute(select(Contact).order_by(Contact.id.desc())).scalars().all()
return render_template('index.html', contacts=rows)
@app.get('/new')
def new():
return render_template('form.html', contact=None)
@app.post('/create')
def create():
name = (request.form.get('name') or '').strip()
email = (request.form.get('email') or '').strip()
phone = (request.form.get('phone') or '').strip()
if not name:
return render_template('form.html', contact={'name': name, 'email': email, 'phone': phone}, error='Imię i nazwisko jest wymagane.')
c = Contact(name=name, email=email or None, phone=phone or None)
db.session.add(c)
db.session.commit()
return redirect(url_for('index'), code=303)
@app.get('/edit/<int:cid>')
def edit(cid: int):
row = db.session.get(Contact, cid)
if not row:
return ('Nie znaleziono kontaktu', 404)
return render_template('form.html', contact=row)
@app.post('/update')
def update():
try:
cid = int(request.form.get('id'))
except (TypeError, ValueError):
return ('Błędny identyfikator', 400)
row = db.session.get(Contact, cid)
if not row:
return ('Nie znaleziono kontaktu', 404)
name = (request.form.get('name') or '').strip()
email = (request.form.get('email') or '').strip()
phone = (request.form.get('phone') or '').strip()
if not name:
return render_template('form.html', contact={'id': cid, 'name': name, 'email': email, 'phone': phone}, error='Imię i nazwisko jest wymagane.')
row.name = name
row.email = email or None
row.phone = phone or None
db.session.commit()
return redirect(url_for('index'), code=303)
@app.post('/delete')
def delete():
try:
cid = int(request.form.get('id'))
except (TypeError, ValueError):
return ('Błędny identyfikator', 400)
row = db.session.get(Contact, cid)
if not row:
return ('Nie znaleziono kontaktu', 404)
db.session.delete(row)
db.session.commit()
return redirect(url_for('index'), code=303)
if __name__ == '__main__':
app.run(debug=True)