113 lines
4.8 KiB
Python
113 lines
4.8 KiB
Python
|
from fastapi import FastAPI, HTTPException
|
|||
|
from fastapi.responses import JSONResponse
|
|||
|
from pydantic import BaseModel, Field
|
|||
|
from uuid import UUID, uuid4
|
|||
|
import requests
|
|||
|
|
|||
|
#Инициализация веб-приложения
|
|||
|
app = FastAPI(title="Publication service")
|
|||
|
|
|||
|
#Строка подключения к авторам
|
|||
|
author_url='http://author_service:8008'
|
|||
|
|
|||
|
#Сущность публикации с полями название, год публикации, ид автора.
|
|||
|
class Publication(BaseModel):
|
|||
|
uuid_: UUID = Field(default_factory=uuid4)
|
|||
|
name: str | None
|
|||
|
public_year: int | None
|
|||
|
author_id: UUID | None
|
|||
|
|
|||
|
#Заранее заполненный список публикаций, в некоторых есть uuid они пригодятся при создании публикаций
|
|||
|
data: list[Publication] = [
|
|||
|
Publication(uuid_="92e78b56-0026-4561-b9f6-ba628110c901", name="книга 1", public_year=2024, author_id="92e78b56-0026-4561-b9f6-ba628110c900"),
|
|||
|
Publication(name="книга 2", public_year=2022, author_id="92e78b56-0026-4561-b9f6-ba628110c900"),
|
|||
|
Publication(name="книга 3", public_year=2003, author_id="3203b355-d844-4d5a-ad91-a9e0135cd9d9"),
|
|||
|
Publication(name="книга 4", public_year=2020, author_id="92e78b56-0026-4561-b9f6-ba628110c900"),
|
|||
|
Publication(name="книга 5", public_year=2019, author_id="3203b355-d844-4d5a-ad91-a9e0135cd9d9")
|
|||
|
]
|
|||
|
|
|||
|
#Получить список всех публикаций
|
|||
|
@app.get("/publication", tags=["Publication"])
|
|||
|
def all_publications():
|
|||
|
return data
|
|||
|
|
|||
|
|
|||
|
#Получить одной публикации по uuid
|
|||
|
@app.get("/publication/{publication_id}", tags=["Publication"])
|
|||
|
def get_publication(publication_id: UUID):
|
|||
|
publication = next((x for x in data if x.uuid_ == publication_id), None)
|
|||
|
|
|||
|
if not publication:
|
|||
|
return HTTPException(status_code=404, detail="Публикация не найдена")
|
|||
|
|
|||
|
return publication
|
|||
|
|
|||
|
#Получить одной публикации по uuid с информацие об ее авторе
|
|||
|
@app.get("/publication/full/{publication_id}")
|
|||
|
def get_full_publication(publication_id: UUID):
|
|||
|
publication = get_publication(publication_id)
|
|||
|
|
|||
|
if not publication:
|
|||
|
return HTTPException(status_code=404, detail="Публикаций не найдена")
|
|||
|
|
|||
|
author = requests.get(f"{author_url}/author/{publication.author_id}")
|
|||
|
|
|||
|
if not author:
|
|||
|
return HTTPException(status_code=404, detail="Автор не найден")
|
|||
|
|
|||
|
result = publication.model_dump()
|
|||
|
result['author_info'] = author.json()
|
|||
|
|
|||
|
return result
|
|||
|
|
|||
|
#Добавление новой публикации, все поля обязательные
|
|||
|
@app.post("/publication", tags=["Publication"])
|
|||
|
def add_publication(name: str, public_year: int, author_id: UUID):
|
|||
|
author = next((x for x in data if x.name == name and x.public_year == public_year and x.author_id == author_id), None)
|
|||
|
|
|||
|
if author:
|
|||
|
return HTTPException(status_code=404, detail="Такая публикация уже существует")
|
|||
|
|
|||
|
try:
|
|||
|
data.append(Publication(name=name, public_year=public_year, author_id=author_id))
|
|||
|
return JSONResponse(content={"message": "Публикация успешно добавлена"}, status_code=200)
|
|||
|
|
|||
|
except Exception as e:
|
|||
|
return HTTPException(status_code=404, detail={"Публикация не была добавлена с ошибкой": str(e)})
|
|||
|
|
|||
|
#Изменение публикации по uuid
|
|||
|
@app.put("/publication/{publication_id}", tags=["Publication"])
|
|||
|
def update_publication(publication_id: UUID, name: str = None, public_year: int = None, author_id: UUID = None):
|
|||
|
publication = get_publication(publication_id)
|
|||
|
|
|||
|
if publication:
|
|||
|
index = data.index(publication)
|
|||
|
if name:
|
|||
|
data[index].name = name
|
|||
|
if public_year:
|
|||
|
data[index].public_year = public_year
|
|||
|
if author_id:
|
|||
|
data[index].author_id = author_id
|
|||
|
return JSONResponse(content={"message": "Публикация успешно изменена"}, status_code=200)
|
|||
|
|
|||
|
else:
|
|||
|
return HTTPException(status_code=404, detail={"Публикация не найдена": {publication}})
|
|||
|
|
|||
|
#Удаление публикации по uuid
|
|||
|
@app.delete("/publication/{publication_id}", tags=["Publication"])
|
|||
|
def delete_publication(publication_id: UUID):
|
|||
|
publication = get_publication(publication_id)
|
|||
|
|
|||
|
if publication:
|
|||
|
index = data.index(publication)
|
|||
|
del data[index]
|
|||
|
|
|||
|
return JSONResponse(content={"message": "Публикация успешно удалена"}, status_code=200)
|
|||
|
|
|||
|
else:
|
|||
|
return HTTPException(status_code=404, detail={"Публикация не найдена": {publication}})
|
|||
|
|
|||
|
#Запуск
|
|||
|
if __name__ == "__main__":
|
|||
|
import uvicorn
|
|||
|
uvicorn.run(app, host="0.0.0.0", port=8009)
|