Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions books/serializer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from books.models import Book
from books.types import SerializedBook


def serialize_book(book: Book) -> SerializedBook:
return {
"title": book.title,
"author_full_name": book.author_full_name,
"year_of_publishing": book.year_of_publishing,
"copies_printed": book.copies_printed,
"short_description": book.short_description,
}
9 changes: 9 additions & 0 deletions books/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from typing import TypedDict


class SerializedBook(TypedDict):
title: str
author_full_name: str
year_of_publishing: int
copies_printed: int
short_description: str
12 changes: 11 additions & 1 deletion books/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views import View

# Create your views here.
from books.models import Book
from books.serializer import serialize_book


class Get_All_Books_Json_View(View):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Подчёркивания лишние, классы называем КемелКейсом

def get(self, request: HttpResponse) -> JsonResponse:
books = Book.objects.all()
books_json = [serialize_book(book) for book in books]
return JsonResponse(data={'data': books_json})
3 changes: 3 additions & 0 deletions bookshelf/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from django.contrib import admin
from django.urls import path

from books.views import Get_All_Books_Json_View

urlpatterns = [
path('admin/', admin.site.urls),
path('api/books/', Get_All_Books_Json_View.as_view()),
]