DAS_2024_1/nikolaeva_yana_lab_3/service_books/app.py
2024-12-10 20:14:57 +04:00

49 lines
1.4 KiB
Python

from flask import Flask, request, jsonify
import requests
from uuid import uuid4
app = Flask(__name__)
books = []
@app.route("/", methods=["GET"])
def list_books():
return jsonify(books)
@app.route("/<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 book:
subscription_response = requests.get(f"http://subscription:5000/{book['subscriptionUuid']}")
if subscription_response.status_code == 200:
book["subscriptionInfo"] = subscription_response.json()
return jsonify(book)
return jsonify({"error": "Not found"}), 404
@app.route("/", methods=["POST"])
def create_book():
data = request.json
new_book = {
"uuid": str(uuid4()),
"author": data["author"],
"subject": data["subject"],
"year": data["year"],
"subscriptionUuid": data["subscriptionUuid"],
}
books.append(new_book)
return jsonify(new_book), 201
@app.route("/<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 book:
book.update(data)
return jsonify(book)
return jsonify({"error": "Not found"}), 404
@app.route("/<uuid:book_id>", methods=["DELETE"])
def delete_book(book_id):
global books
books = [b for b in books if b["uuid"] != str(book_id)]
return "", 204