DAS_2024_1/pupkov_alexey_lab_3/services/book/app.py

64 lines
1.7 KiB
Python
Raw Normal View History

2024-11-16 22:33:29 +04:00
from flask import Flask, request, jsonify
import uuid
import requests
app = Flask(__name__)
# Хранилище данных
books = []
SUBSCRIPTION_SERVICE_URL = "http://subscription-service:5000/api/subscriptions/"
@app.route('/api/books/', methods=['GET'])
def get_books():
return jsonify(books), 200
@app.route('/api/books/<uuid:uuid>', methods=['GET'])
def get_book(uuid):
book = next((b for b in books if b['uuid'] == str(uuid)), None)
if not book:
return jsonify({'error': 'Book not found'}), 404
subscription_uuid = book['subscriptionUuid']
subscription = requests.get(f"{SUBSCRIPTION_SERVICE_URL}{subscription_uuid}").json()
book['subscriptionInfo'] = subscription
return jsonify(book), 200
@app.route('/api/books/', methods=['POST'])
def create_book():
data = request.json
book = {
'uuid': str(uuid.uuid4()),
'author': data['author'],
'subject': data['subject'],
'year': data['year'],
'subscriptionUuid': data['subscriptionUuid']
}
books.append(book)
return jsonify(book), 201
@app.route('/api/books/<uuid:uuid>', methods=['PUT'])
def update_book(uuid):
data = request.json
book = next((b for b in books if b['uuid'] == str(uuid)), None)
if not book:
return jsonify({'error': 'Book not found'}), 404
book.update({
'author': data['author'],
'subject': data['subject'],
'year': data['year'],
'subscriptionUuid': data['subscriptionUuid']
})
return jsonify(book), 200
@app.route('/api/books/<uuid:uuid>', methods=['DELETE'])
def delete_book(uuid):
global books
books = [b for b in books if b['uuid'] != str(uuid)]
return '', 204
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001)