Digitale bierlijst

settlements.py 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """
  2. Provides routes for managing Settlement objects.
  3. """
  4. from sqlalchemy.exc import SQLAlchemyError
  5. from flask import jsonify, request
  6. from piket_server.flask import app, db
  7. from piket_server.models import Consumption, Settlement
  8. @app.route("/settlements", methods=["GET"])
  9. def get_settlements():
  10. """ Return a list of the active Settlements. """
  11. result = Settlement.query.all()
  12. return jsonify(settlements=[s.as_dict for s in result])
  13. @app.route("/settlements/<int:settlement_id>", methods=["GET"])
  14. def get_settlement(settlement_id: int):
  15. """ Show full details for a single Settlement. """
  16. s = Settlement.query.get_or_404(settlement_id)
  17. per_person = s.per_person
  18. return jsonify(settlement=s.as_dict, count_info=per_person)
  19. @app.route("/settlements", methods=["POST"])
  20. def add_settlement():
  21. """ Create a Settlement, and link all un-settled Consumptions to it. """
  22. json = request.get_json()
  23. if not json:
  24. return jsonify({"error": "Could not parse JSON."}), 400
  25. data = json.get("settlement") or {}
  26. s = Settlement(name=data["name"])
  27. db.session.add(s)
  28. db.session.commit()
  29. Consumption.query.filter_by(settlement=None).update(
  30. {"settlement_id": s.settlement_id}
  31. )
  32. db.session.commit()
  33. return jsonify(settlement=s.as_dict, count_info=s.per_person)