flask_crud_app/routes/create.py

33 lines
1.3 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 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-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-06 08:33:13 +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
form_data = {attrib: request.form[attrib] for attrib in item_attributes}
2025-01-30 07:37:21 +00:00
try:
2025-02-07 06:31:55 +00:00
primary_attr = next((attrib_name for attrib_name, attrib in item_attributes.items() if attrib.primary), None)
2025-01-30 07:37:21 +00:00
except ValueError:
2025-02-07 18:20:26 +00:00
return render_template('create.html', item_attributes=item_attributes, exc=primary_attr)
2025-01-30 07:37:21 +00:00
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()
except exc.IntegrityError:
2025-02-07 18:20:26 +00:00
return render_template('create.html', item_attributes=item_attributes, exc='integrity')
2025-01-30 07:37:21 +00:00
except exc.StatementError:
2025-02-07 18:20:26 +00:00
return render_template('create.html', item_attributes=item_attributes, exc='status')
2025-01-30 07:37:21 +00:00
return redirect('/viewall')