""" Provides routes for managing Export objects. """ from flask import jsonify from sqlalchemy.exc import SQLAlchemyError from piket_server.flask import app, db from piket_server.models import Export, Settlement @app.route("/exports", methods=["GET"]) def get_exports(): """ Return a list of the created Exports. """ result = Export.query.all() return jsonify(exports=[e.as_dict for e in result]) @app.route("/exports/", methods=["GET"]) def get_export(export_id: int): """ Return an overview for the given Export. """ e = Export.query.get_or_404(export_id) ss = [s.as_dict for s in e.settlements] return jsonify(export=e.as_dict, settlements=ss) @app.route("/exports", methods=["POST"]) def add_export(): """ Create an Export, and link all un-exported Settlements to it. """ # Assert that there are Settlements to be exported. s_count = Settlement.query.filter_by(export=None).count() if s_count == 0: return jsonify(error="No un-exported Settlements."), 403 e = Export() db.session.add(e) db.session.commit() Settlement.query.filter_by(export=None).update({"export_id": e.export_id}) db.session.commit() ss = [s.as_dict for s in e.settlements] return jsonify(export=e.as_dict, settlements=ss), 201