flask_crud_app/routes/update.py

54 lines
2.5 KiB
Python
Raw Normal View History

2025-01-30 07:37:21 +00:00
from flask import Blueprint, request, render_template, redirect
2025-02-11 18:45:53 +00:00
from definitions.models import Asset, db
2025-02-06 10:43:09 +00:00
from config import item_attributes
2025-02-07 18:34:43 +00:00
from sqlalchemy import exc # Import exc for database exceptions
from functions.validate_values import validate_values # Form validation
2025-01-30 07:37:21 +00:00
update_bp = Blueprint('editasset', __name__)
2025-02-07 19:58:37 +00:00
@update_bp.route('/update/<string:primary_value>/', methods=['GET', 'POST'])
def update(primary_value):
# Identify the primary attribute
primary_attrib = next((attrib for attrib in item_attributes if attrib.primary), None)
2025-02-07 19:58:37 +00:00
if not primary_attrib:
return "Primary attribute not defined in configuration."
# Fetch the item using the primary attribute
item = Asset.query.filter_by(**{primary_attrib.attrib_name: primary_value}).first()
2025-02-07 18:34:43 +00:00
if not item:
return f"{primary_attrib.display_name} '{primary_value}' not found."
2025-02-07 18:34:43 +00:00
if request.method == 'GET':
# Render the update form with the current item data
return render_template('update.html', item=item, item_attributes=item_attributes)
2025-02-07 18:34:43 +00:00
2025-01-30 07:37:21 +00:00
if request.method == 'POST':
# Get data from form
form_data = {attrib.attrib_name: request.form.get(attrib.attrib_name) for attrib in item_attributes}
2025-02-07 18:34:43 +00:00
# Form validation
error = validate_values(form_data)
if error:
return render_template('update.html', item=item, item_attributes=item_attributes, error=error)
2025-01-30 07:37:21 +00:00
2025-02-07 18:34:43 +00:00
# Update the item with the new data
for attrib in item_attributes:
setattr(item, attrib.attrib_name, form_data[attrib.attrib_name])
2025-01-30 07:37:21 +00:00
2025-02-07 18:34:43 +00:00
try:
db.session.commit()
except exc.IntegrityError:
# Handle duplicate primary key or unique constraint errors
error = f"An entry with {primary_attrib.display_name} '{form_data[primary_attrib.attrib_name]}' already exists."
return render_template('update.html', item=item, item_attributes=item_attributes, error=error)
except exc.StatementError as e:
# Handle other database errors
error = f"Database error: {str(e)}"
return render_template('update.html', item=item, item_attributes=item_attributes, error=error)
except Exception as e:
# Handle unexpected errors
error = f"An unexpected error occurred: {str(e)}"
return render_template('update.html', item=item, item_attributes=item_attributes, error=error)
# Redirect to /viewall on success
2025-02-07 18:34:43 +00:00
return redirect('/viewall')