Started basic /books route. Got file and image saving. Started route documentation in README.md

tyler
XxMistaCruzxX 2024-02-02 13:36:47 -05:00
parent e0393611cf
commit cde12d6b28
5 changed files with 145 additions and 43 deletions

73
README.md Normal file
View File

@ -0,0 +1,73 @@
# Alt-Text Backend
## ROUTES
### /books
#### GET
##### FUNCTION
Gets a list of books from database
##### PARAMS
- query (string) | ensures book titles must have query as a substring
- skip (int) | skips skip amount of books from the result
- limit (int) | limits the amount of books returned to limit
##### RETURNS
```
[
{
title: string,
description: string,
cover: string,
},
...
]
```
#### POST
##### FUNCTION
Adds a book to the database and starts initial processing
##### FIELDS
- title (string) | desired title for new book
- description (string) | desired description for new book
- cover (image_file) | desired cover image for new book
- file (file[.zip]) | book file (html and images bundled)
##### RETURNS
```
{
title: string,
description: string,
cover: string,
}
```
### /books/:bookid
#### GET
#### PATCH
#### DELETE
### /books/:bookid/images
#### GET
#### PATCH
### /books/:bookid/images/:imagesrc
#### GET
#### PATCH

View File

@ -14,13 +14,13 @@ Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from .views import BooksView, ImagesView
from .views import BooksView # , ImagesView
urlpatterns = [
path("admin/", admin.site.urls),
path("api-auth/", include("rest_framework.urls")),
# path("admin/", admin.site.urls),
# path("api-auth/", include("rest_framework.urls")),
path("api/books", BooksView.as_view()),
path("api/images", ImagesView.as_view()),
]

View File

@ -1,55 +1,84 @@
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import permissions
from rest_framework import serializers
from rest_framework import status, permissions, serializers
from rest_framework.exceptions import ValidationError
from rest_framework.parsers import FormParser, MultiPartParser
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from uuid import uuid4
class BookSerializer(serializers.Serializer):
bookdata = serializers.CharField()
class ImageSerializer(serializers.Serializer):
imagedata = serializers.CharField()
beforeContext = serializers.CharField(required=False)
afterContext = serializers.CharField(required=False)
title = serializers.CharField()
description = serializers.CharField()
cover = serializers.ImageField()
file = serializers.FileField()
class BooksView(APIView):
parser_classes = (FormParser, MultiPartParser)
serializer_class = BookSerializer
def get(self, request, *args, **kwargs):
data = {"books": "this is a book"}
# TODO: get's list of books given limits
data = {"books": []}
return Response(data, status=status.HTTP_200_OK)
def post(self, request, *args, **kwargs):
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
validated_data = serializer.validated_data
return Response(
{"book": validated_data.get("bookdata")},
status=status.HTTP_201_CREATED,
)
else:
# validate request data
serializer = self.serializer_class(data=request.data)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
validated_data = serializer.validated_data
class ImagesView(APIView):
def get(self, request, *args, **kwargs):
data = {"images": "this is an image"}
return Response(data, status=status.HTTP_200_OK)
def post(self, request, *args, **kwargs):
serializer = ImageSerializer(data=request.data)
if serializer.is_valid():
validated_data = serializer.validated_data
res = {"book": validated_data.get("imagedata")}
if validated_data.get("beforeContext"):
res["beforeContext"] = validated_data.get("beforeContext")
if validated_data.get("afterContext"):
res["afterContext"] = validated_data.get("afterContext")
# perform initial book processing
file = validated_data["file"]
if not file.name.endswith(".zip"):
return Response(
res,
status=status.HTTP_201_CREATED,
{"file": ["file must be a zip"]}, status=status.HTTP_400_BAD_REQUEST
)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
id = uuid4()
books_path = "./books/"
default_storage.save(f"{books_path}{str(id)}.zip", ContentFile(file.read()))
# save cover image
covers_path = "./covers/"
default_storage.save(
f"{covers_path}{str(id)}.{validated_data['cover'].name.split('.')[-1]}",
ContentFile(validated_data["cover"].read()),
)
return Response(
{
"book": validated_data.get("title"),
"description": validated_data.get("description"),
},
status=status.HTTP_201_CREATED,
)
# class ImageSerializer(serializers.Serializer):
# imagedata = serializers.CharField()
# beforeContext = serializers.CharField(required=False)
# afterContext = serializers.CharField(required=False)
# class ImagesView(APIView):
# def get(self, request, *args, **kwargs):
# data = {"images": "this is an image"}
# return Response(data, status=status.HTTP_200_OK)
# def post(self, request, *args, **kwargs):
# serializer = ImageSerializer(data=request.data)
# if serializer.is_valid():
# validated_data = serializer.validated_data
# res = {"book": validated_data.get("imagedata")}
# if validated_data.get("beforeContext"):
# res["beforeContext"] = validated_data.get("beforeContext")
# if validated_data.get("afterContext"):
# res["afterContext"] = validated_data.get("afterContext")
# return Response(
# res,
# status=status.HTTP_201_CREATED,
# )
# else:
# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)