flask_crud_app/routes/create.py

49 lines
2.1 KiB
Python
Raw Normal View History

2025-02-23 17:27:18 +00:00
from flask import Blueprint, request, render_template, redirect, flash
2025-02-11 18:45:53 +00:00
from definitions.models import Asset, db
2025-02-06 08:33:13 +00:00
from config import item_attributes
2025-02-11 20:45:25 +00:00
from sqlalchemy import exc # Import exc for database exceptions
2025-02-23 17:27:18 +00:00
from functions.validate_values import validate_values # Form validation
2025-01-30 07:37:21 +00:00
addasset_bp = Blueprint('addasset', __name__)
@addasset_bp.route('/create/', methods=['GET', 'POST'])
def create():
if request.method == 'GET':
2025-02-07 06:31:55 +00:00
# Render the "add item" form
2025-02-23 17:27:18 +00:00
return render_template('create.html', item_attributes=item_attributes)
2025-01-30 07:37:21 +00:00
2025-02-07 06:31:55 +00:00
# Process submitted form
2025-01-30 07:37:21 +00:00
if request.method == 'POST':
2025-02-07 06:31:55 +00:00
# Get data from form
2025-02-23 17:27:18 +00:00
form_data = {attrib.attrib_name: request.form.get(attrib.attrib_name) for attrib in item_attributes}
2025-02-23 17:27:18 +00:00
# Form validation
error = validate_values(form_data)
if error:
return render_template('create.html', item_attributes=item_attributes, error=error)
2025-01-30 07:37:21 +00:00
# Create the Asset object
2025-02-07 06:31:55 +00:00
item = Asset(**form_data)
2025-01-30 07:37:21 +00:00
try:
db.session.add(item)
db.session.commit()
2025-02-23 17:27:18 +00:00
except exc.IntegrityError as e:
# Handle duplicate primary key or unique constraint errors
primary_attrib = next((attrib for attrib in item_attributes if attrib.primary), None)
if primary_attrib:
error = f"An entry with {primary_attrib.display_name} '{form_data[primary_attrib.attrib_name]}' already exists."
else:
error = "An entry with the same primary key already exists."
return render_template('create.html', item_attributes=item_attributes, error=error)
except exc.StatementError as e:
# Handle other database errors
error = f"Database error: {str(e)}"
return render_template('create.html', item_attributes=item_attributes, error=error)
except Exception as e:
# Handle unexpected errors
error = f"An unexpected error occurred: {str(e)}"
return render_template('create.html', item_attributes=item_attributes, error=error)
# Redirect to /viewall on success
2025-01-30 07:37:21 +00:00
return redirect('/viewall')