-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
56 lines (43 loc) · 1.38 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from enum import Enum
from operator import attrgetter
from typing import Optional
from fastapi import FastAPI, Query, Depends
from fastapi.responses import FileResponse
from fastapi_utilities import repeat_every
from pydantic import BaseModel, Field
from contextlib import asynccontextmanager
from random import shuffle
import lib
class SortMethod(str, Enum):
random = "random"
az = "az"
za = "za"
recent = "recent"
class ListBooksQuery(BaseModel):
sort: Optional[SortMethod] = Field(Query(default=SortMethod.random))
@asynccontextmanager
async def lifespan(app: FastAPI):
lib.parse_library()
yield
@repeat_every(seconds=60*60)
async def reparse_library():
lib.parse_library()
app = FastAPI(lifespan=lifespan)
@app.get("/list-books")
def list_books(sort: SortMethod = SortMethod.recent):
books = lib.list_books()
if sort is SortMethod.random:
shuffle(books)
elif sort is SortMethod.az:
books.sort(key=attrgetter("title"), reverse=False)
elif sort is SortMethod.za:
books.sort(key=attrgetter("title"), reverse=True)
elif sort is SortMethod.recent:
books.sort(key=attrgetter("last_updated"), reverse=True)
return books
@app.get("/download/{id}")
def download(id: str):
path, filename = lib.download_book(id)
return FileResponse(
path=path, media_type="application/octet-stream", filename=filename
)