DAS_2024_1/polevoy_sergey_lab_3/service_service/app.py

67 lines
2.1 KiB
Python

import requests
from flask import Flask, jsonify, request
import uuid
app = Flask(__name__)
services = {}
@app.route('/', methods=['GET'])
def get_services():
return jsonify(list(services.values()))
@app.route('/<uuid:service_uuid>', methods=['GET'])
def get_service(service_uuid):
if str(service_uuid) in services:
service = services[str(service_uuid)].copy()
tariffs_list = []
try:
response = requests.get(f'http://tariff:5001/with-service/{service_uuid}')
tariffs_list = response.json()
except requests.exceptions.RequestException:
pass
service['tariffs'] = tariffs_list
return jsonify(service)
return jsonify({'message': 'Service not found'}), 404
@app.route('/', methods=['POST'])
def create_service():
data = request.get_json()
if not data or 'name' not in data or 'description' not in data:
return jsonify({'message': 'Invalid data. Name and description are required'}), 400
service_uuid = str(uuid.uuid4())
services[service_uuid] = {'uuid': service_uuid, 'name': data['name'], 'description': data['description']}
return jsonify(services[service_uuid]), 201
@app.route('/<uuid:service_uuid>', methods=['PUT'])
def update_service(service_uuid):
if str(service_uuid) not in services:
return jsonify({'message': 'Service not found'}), 404
data = request.get_json()
if not data or 'name' not in data or 'description' not in data:
return jsonify({'message': 'Invalid data'}), 400
services[str(service_uuid)]['name'] = data['name']
services[str(service_uuid)]['description'] = data['description']
return jsonify(services[str(service_uuid)]), 200
@app.route('/<uuid:service_uuid>', methods=['DELETE'])
def delete_service(service_uuid):
if str(service_uuid) in services:
del services[str(service_uuid)]
return jsonify({'message': 'Service deleted'}), 200
return jsonify({'message': 'Service not found'}), 404
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)