DAS_2024_1/kashin_maxim_lab_3/faculty_service/app.py

43 lines
1.5 KiB
Python
Raw Normal View History

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'])
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})
if __name__ == '__main__':
app.run(host='0.0.0.0', use_reloader=False, port=8082)