DAS_2023_1/antonov_dmitry_lab_3/service_a/app.py
2023-12-04 18:24:11 +04:00

100 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from flask import Flask, jsonify, request
import requests
app = Flask(__name__)
# набор данных докторов с их пациентами
doctors_data = [
{
'id': 1,
'name': 'Doctor A',
'email': 'doctor.a@example.com',
'patients': [
{'id': 1, 'name': 'Patient A1', 'email': 'patient.a1@example.com'},
{'id': 2, 'name': 'Patient A2', 'email': 'patient.a2@example.com'},
],
},
{
'id': 2,
'name': 'Doctor B',
'email': 'doctor.b@example.com',
'patients': [
{'id': 3, 'name': 'Patient B1', 'email': 'patient.b1@example.com'},
{'id': 4, 'name': 'Patient B2', 'email': 'patient.b2@example.com'},
],
},
{
'id': 3,
'name': 'Doctor C',
'email': 'doctor.c@example.com',
'patients': [
{'id': 5, 'name': 'Patient C1', 'email': 'patient.c1@example.com'},
],
},
]
# URL для сервиса пациентов
patients_service_url = "http://localhost/app2/patients"
@app.route('/', methods=['GET'])
def get_index():
return "это первый сервис"
@app.route('/doctors', methods=['GET'])
def get_doctors():
return jsonify(doctors_data)
@app.route('/doctors', methods=['POST'])
def create_doctor():
new_doctor = request.json
# уникальный id для нового доктора
new_doctor['id'] = len(doctors_data) + 1
new_doctor['patients'] = []
doctors_data.append(new_doctor)
return jsonify(new_doctor), 201
@app.route('/doctors/<int:id>', methods=['PUT'])
def update_doctor(id):
for doctor in doctors_data:
if doctor['id'] == id:
doctor.update(request.json)
return jsonify(doctor), 200
return jsonify({'error': 'Доктор не найден'}), 404
@app.route('/doctors/<int:id>', methods=['DELETE'])
def delete_doctor(id):
global doctors_data
doctors_data = [doctor for doctor in doctors_data if doctor['id'] != id]
return jsonify({'message': 'Доктор удален'}), 200
@app.route('/doctors/<int:id>/patients', methods=['GET'])
def get_doctor_patients(id):
for doctor in doctors_data:
if doctor['id'] == id:
return jsonify(doctor['patients'])
return jsonify({'error': 'Доктор не найден'}), 404
@app.route('/doctors/<int:id>/patients', methods=['POST'])
def create_doctor_patient(id):
for doctor in doctors_data:
if doctor['id'] == id:
new_patient = request.json
# назначить уникальный id новому пациенту
new_patient['id'] = len(doctor['patients']) + 1
doctor['patients'].append(new_patient)
requests.post(patients_service_url, json=new_patient)
return jsonify(new_patient), 201
return jsonify({'error': 'Доктор не найден'}), 404
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)