2024-11-21 04:43:58 +04:00
|
|
|
|
from flask import Flask, jsonify, request
|
|
|
|
|
import requests
|
|
|
|
|
import uuid
|
|
|
|
|
|
2024-12-17 20:57:11 +04:00
|
|
|
|
|
2024-11-21 04:43:58 +04:00
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
# Данные о книгах (в памяти)
|
|
|
|
|
books = [
|
|
|
|
|
{
|
|
|
|
|
"uuid": str(uuid.uuid4()),
|
|
|
|
|
"author": "J.K.R.",
|
|
|
|
|
"subject": "HP and PS",
|
|
|
|
|
"year": 1997,
|
|
|
|
|
"subscriptionUuid": "8f036445-a5bd-401c-926e-840f9de795cd"
|
|
|
|
|
}
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
SUBSCRIPTIONS_URL = "http://subscriptions_service:5000/subscriptions/"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.route('/books/', methods=['GET'])
|
|
|
|
|
def get_books():
|
|
|
|
|
return jsonify(books), 200
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.route('/books/<uuid:book_id>', methods=['GET'])
|
|
|
|
|
def get_book(book_id):
|
|
|
|
|
book = next((b for b in books if b['uuid'] == str(book_id)), None)
|
|
|
|
|
if not book:
|
|
|
|
|
return jsonify({"error": "Book not found"}), 404
|
|
|
|
|
|
|
|
|
|
# Получение данных об абонементе
|
|
|
|
|
response = requests.get(f"{SUBSCRIPTIONS_URL}{book['subscriptionUuid']}")
|
|
|
|
|
if response.status_code == 200:
|
|
|
|
|
book["subscriptionInfo"] = response.json()
|
|
|
|
|
return jsonify(book), 200
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.route('/books/', methods=['POST'])
|
|
|
|
|
def create_book():
|
|
|
|
|
data = request.json
|
|
|
|
|
new_book = {
|
|
|
|
|
"uuid": str(uuid.uuid4()),
|
|
|
|
|
"author": data["author"],
|
|
|
|
|
"subject": data["subject"],
|
|
|
|
|
"year": data["year"],
|
|
|
|
|
"subscriptionUuid": data["subscriptionUuid"]
|
|
|
|
|
}
|
|
|
|
|
books.append(new_book)
|
|
|
|
|
return jsonify(new_book), 201
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.route('/books/<uuid:book_id>', methods=['PUT'])
|
|
|
|
|
def update_book(book_id):
|
|
|
|
|
data = request.json
|
|
|
|
|
book = next((b for b in books if b['uuid'] == str(book_id)), None)
|
|
|
|
|
if not book:
|
|
|
|
|
return jsonify({"error": "Book not found"}), 404
|
|
|
|
|
|
|
|
|
|
# Обновляем данные книги
|
|
|
|
|
book["author"] = data.get("author", book["author"])
|
|
|
|
|
book["subject"] = data.get("subject", book["subject"])
|
|
|
|
|
book["year"] = data.get("year", book["year"])
|
|
|
|
|
book["subscriptionUuid"] = data.get("subscriptionUuid", book["subscriptionUuid"])
|
|
|
|
|
|
|
|
|
|
return jsonify(book), 200
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.route('/books/<uuid:book_id>', methods=['DELETE'])
|
|
|
|
|
def delete_book(book_id):
|
|
|
|
|
global books
|
|
|
|
|
book = next((b for b in books if b['uuid'] == str(book_id)), None)
|
|
|
|
|
if not book:
|
|
|
|
|
return jsonify({"error": "Book not found"}), 404
|
|
|
|
|
|
|
|
|
|
# Удаляем книгу
|
|
|
|
|
books = [b for b in books if b['uuid'] != str(book_id)]
|
|
|
|
|
return jsonify({"message": "Book deleted successfully"}), 200
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
app.run(host="0.0.0.0", port=5000)
|