from flask import Flask, jsonify, request, Response from service import FacultyService from db import db app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://faculty_user:password@faculty_db:5432/facultydb' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(app) faculty_service = FacultyService() @app.route('/faculties', methods=['GET', 'POST']) def handle_faculties(): if request.method == 'POST': dto = request.get_json()['dto'] faculty = faculty_service.create_faculty(dto['name'], dto['university_id']) if isinstance(faculty, dict): return jsonify({"id": faculty['id'], "name": faculty['name'], "university_id": faculty['university_id']}) return jsonify({"id": faculty.id, "name": faculty.name, "university_id": faculty.university_id}) return jsonify(faculty_service.get_all_faculties()) @app.route('/faculties/<int:faculty_id>', methods=['GET', 'PUT', 'DELETE']) def handle_faculty(faculty_id): if request.method == 'PUT': dto = request.get_json()['dto'] updated_faculty = faculty_service.update_faculty(faculty_id, dto['name']) if updated_faculty: return jsonify(updated_faculty) else: return Response(status=404) elif request.method == 'DELETE': faculty_service.delete_faculty(faculty_id) return Response(status=200) university = faculty_service.get_faculty(faculty_id) return jsonify({"id": university.id, "name": university.name, "university_id": university.university_id}) @app.route('/faculties/<int:faculty_id>/universities', methods=['POST']) def add_university(faculty_id): dto = request.get_json() university_id = dto['university_id'] faculty_service.add_university_to_faculty(faculty_id, university_id) return Response(status=204) @app.route('/faculties/<int:faculty_id>/universities/<int:university_id>', methods=['DELETE']) def remove_university(faculty_id, university_id): faculty_service.remove_university_from_faculty(faculty_id, university_id) return Response(status=204) if __name__ == '__main__': app.run(host='0.0.0.0', use_reloader=False, port=8082)