From a3827d5b4b82db08c679d476c25ca48c7433e006 Mon Sep 17 00:00:00 2001 From: yasha Date: Sat, 14 Dec 2024 01:21:48 +0400 Subject: [PATCH] fadeeva_nastya_lab_3 is ready --- fadeeva_nastya_lab_3/README.md | 38 +++++++++++++ .../discipline_service/Dockerfile | 10 ++++ .../discipline_service/main.py | 56 +++++++++++++++++++ .../discipline_service/requirements.txt | 1 + fadeeva_nastya_lab_3/docker-compose.yml | 24 ++++++++ fadeeva_nastya_lab_3/nginx/nginx.conf | 11 ++++ .../teacher_service/Dockerfile | 10 ++++ fadeeva_nastya_lab_3/teacher_service/main.py | 54 ++++++++++++++++++ .../teacher_service/requirements.txt | 1 + 9 files changed, 205 insertions(+) create mode 100644 fadeeva_nastya_lab_3/README.md create mode 100644 fadeeva_nastya_lab_3/discipline_service/Dockerfile create mode 100644 fadeeva_nastya_lab_3/discipline_service/main.py create mode 100644 fadeeva_nastya_lab_3/discipline_service/requirements.txt create mode 100644 fadeeva_nastya_lab_3/docker-compose.yml create mode 100644 fadeeva_nastya_lab_3/nginx/nginx.conf create mode 100644 fadeeva_nastya_lab_3/teacher_service/Dockerfile create mode 100644 fadeeva_nastya_lab_3/teacher_service/main.py create mode 100644 fadeeva_nastya_lab_3/teacher_service/requirements.txt diff --git a/fadeeva_nastya_lab_3/README.md b/fadeeva_nastya_lab_3/README.md new file mode 100644 index 0000000..ed15a76 --- /dev/null +++ b/fadeeva_nastya_lab_3/README.md @@ -0,0 +1,38 @@ +# Лабораторная работа №3 - REST API, Gateway и синхронный обмен между микросервисами + +## Задание + ++ Создать 2 микросервиса, реализующих CRUD на связанных сущностях. ++ Реализовать механизм синхронного обмена сообщениями между микросервисами. ++ Реализовать шлюз на основе прозрачного прокси-сервера nginx. + +### Микросервисы +1. **teacher_service** — сервис, который управляет информацией о пользователях + +2. **discipline_service** — сервис, который обрабатывает данные о заказах пользователей. + +### Критерии + ++ Микросервисы должны быть связаны как 1-ко-многим. +Например, учитель (teacher) может преподовать несколько дисциплин (discipline). + +## Описание работы + +Данная лабораторная работа написана на языке - pyton. + +1. Реализация синхронного обмена + +Сервис **teacher_service** отправляет HTTP-запросы к сервису **discipline_service** при выполнении определенных операций CRUD. Тем самым получим актуальную информацию о дисциплинах, связанных с конкретными учителем. + +2. Реализация gateway при помощи nginx + +Конфигурационный файл **Nginx** определяет настройки веб-сервера и обратного прокси. Он управляет входящими запросами и направляет их на соответствующие сервисы. + +3. Docker Compose + +Конфигурационный файл docker-compose.yml - это многоконтейнерное приложение, которое включает в себя три сервиса: teacher_servic, discipline_service и nginx. + +# Видеозапись работы программмы + +https://vkvideo.ru/video186826232_456239554 + diff --git a/fadeeva_nastya_lab_3/discipline_service/Dockerfile b/fadeeva_nastya_lab_3/discipline_service/Dockerfile new file mode 100644 index 0000000..851c5df --- /dev/null +++ b/fadeeva_nastya_lab_3/discipline_service/Dockerfile @@ -0,0 +1,10 @@ +FROM python:3.11 + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +CMD ["python", "main.py"] \ No newline at end of file diff --git a/fadeeva_nastya_lab_3/discipline_service/main.py b/fadeeva_nastya_lab_3/discipline_service/main.py new file mode 100644 index 0000000..9c8da2e --- /dev/null +++ b/fadeeva_nastya_lab_3/discipline_service/main.py @@ -0,0 +1,56 @@ +from flask import Flask, jsonify, request +import uuid + +app = Flask(__name__) + +disciplines = {} + +# вывод всех заказов +@app.route('/disciplines', methods=['GET']) +def get_disciplines(): + return jsonify(list(disciplines.values())) + +# получение заказа по uuid +@app.route('/disciplines/', methods=['GET']) +def get_discipline(discipline_uuid): + discipline = disciplines.get(str(discipline_uuid)) + if discipline: + return jsonify(discipline) + return jsonify({'error': 'Not found'}), 404 + +# добавление нового заказа +@app.route('/disciplines', methods=['POST']) +def create_discipline(): + data = request.json + discipline_uuid = str(uuid.uuid4()) + discipline = { + 'uuid': discipline_uuid, + 'number': data['number'], + 'discipline': data['discipline'], + 'teacher_uuid': data['teacher_uuid'] + } + disciplines[discipline_uuid] = discipline + return jsonify(discipline), 201 + +# изменение заказа по uuid +@app.route('/disciplines/', methods=['PUT']) +def update_discipline(discipline_uuid): + discipline = disciplines.get(str(discipline_uuid)) + if not discipline: + return jsonify({'error': 'Not found'}), 404 + data = request.json + discipline['number'] = data['number'] + discipline['discipline'] = data['discipline'] + discipline['teacher_uuid'] = data['teacher_uuid'] + return jsonify(discipline) + +# удаление заказа по uuid +@app.route('/disciplines/', methods=['DELETE']) +def delete_discipline(discipline_uuid): + if str(discipline_uuid) in disciplines: + del disciplines[str(discipline_uuid)] + return '', 204 + return jsonify({'error': 'Not found'}), 404 + +if __name__ == '__main__': + app.run(host='0.0.0.0', port=5001) \ No newline at end of file diff --git a/fadeeva_nastya_lab_3/discipline_service/requirements.txt b/fadeeva_nastya_lab_3/discipline_service/requirements.txt new file mode 100644 index 0000000..2077213 --- /dev/null +++ b/fadeeva_nastya_lab_3/discipline_service/requirements.txt @@ -0,0 +1 @@ +Flask \ No newline at end of file diff --git a/fadeeva_nastya_lab_3/docker-compose.yml b/fadeeva_nastya_lab_3/docker-compose.yml new file mode 100644 index 0000000..eb23633 --- /dev/null +++ b/fadeeva_nastya_lab_3/docker-compose.yml @@ -0,0 +1,24 @@ +services: + teacher_service: + build: + context: ./teacher_service + dockerfile: Dockerfile + ports: + - "5000:5000" + + discipline_service: + build: + context: ./discipline_service + dockerfile: Dockerfile + ports: + - "5001:5001" + + nginx: + image: nginx:latest + volumes: + - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf + ports: + - "80:80" + depends_on: + - teacher_service + - discipline_service \ No newline at end of file diff --git a/fadeeva_nastya_lab_3/nginx/nginx.conf b/fadeeva_nastya_lab_3/nginx/nginx.conf new file mode 100644 index 0000000..860e84a --- /dev/null +++ b/fadeeva_nastya_lab_3/nginx/nginx.conf @@ -0,0 +1,11 @@ +server { + listen 80; + + location /teachers { + proxy_pass http://teacher_service:5000; + } + + location /disciplines { + proxy_pass http://discipline_service:5001; + } +} \ No newline at end of file diff --git a/fadeeva_nastya_lab_3/teacher_service/Dockerfile b/fadeeva_nastya_lab_3/teacher_service/Dockerfile new file mode 100644 index 0000000..851c5df --- /dev/null +++ b/fadeeva_nastya_lab_3/teacher_service/Dockerfile @@ -0,0 +1,10 @@ +FROM python:3.11 + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +CMD ["python", "main.py"] \ No newline at end of file diff --git a/fadeeva_nastya_lab_3/teacher_service/main.py b/fadeeva_nastya_lab_3/teacher_service/main.py new file mode 100644 index 0000000..9f671b8 --- /dev/null +++ b/fadeeva_nastya_lab_3/teacher_service/main.py @@ -0,0 +1,54 @@ +from flask import Flask, jsonify, request +import uuid + +app = Flask(__name__) + +teachers = {} + +# вывод всех пользователей +@app.route('/teachers', methods=['GET']) +def get_teachers(): + return jsonify(list(teachers.values())) + +# получение пользователя по uuid +@app.route('/teachers/', methods=['GET']) +def get_teacher(teacher_uuid): + teacher = teachers.get(str(teacher_uuid)) + if teacher: + return jsonify(teacher) + return jsonify({'error': 'Not found'}), 404 + +# добавление нового пользователя +@app.route('/teachers', methods=['POST']) +def create_teacher(): + data = request.get_json() + teacher_uuid = str(uuid.uuid4()) + teacher = { + 'uuid': teacher_uuid, + 'name': data['name'], + 'age': data['age'] + } + teachers[teacher_uuid] = teacher + return jsonify(teacher), 201 + +# изменение пользователя по uuid +@app.route('/teachers/', methods=['PUT']) +def update_teacher(teacher_uuid): + teacher = teachers.get(str(teacher_uuid)) + if not teacher: + return jsonify({'error': 'Not found'}), 404 + data = request.get_json() + teacher['name'] = data['name'] + teacher['age'] = data['age'] + return jsonify(teacher) + +# удаление пользователя по uuid +@app.route('/teachers/', methods=['DELETE']) +def delete_teacher(teacher_uuid): + if str(teacher_uuid) in teachers: + del teachers[str(teacher_uuid)] + return '', 204 + return jsonify({'error': 'Not found'}), 404 + +if __name__ == '__main__': + app.run(host='0.0.0.0', port=5000) \ No newline at end of file diff --git a/fadeeva_nastya_lab_3/teacher_service/requirements.txt b/fadeeva_nastya_lab_3/teacher_service/requirements.txt new file mode 100644 index 0000000..2077213 --- /dev/null +++ b/fadeeva_nastya_lab_3/teacher_service/requirements.txt @@ -0,0 +1 @@ +Flask \ No newline at end of file