-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubapi.py
116 lines (94 loc) · 2.86 KB
/
pubapi.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import uvicorn
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from fastapi import FastAPI, HTTPException, status, Depends
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from starlette.requests import Request
from pydantic import BaseModel
from glob import glob
from pathlib import Path
ABSOLUTE_PATH = "/var/www/aaaa/"
limiter = Limiter(key_func=get_remote_address)
app = FastAPI(root_path="/api/public")
app.state.limiter = limiter
app.add_exception_handler(HTTPException, _rate_limit_exceeded_handler)
origins = [
"http://lobadk.com",
"https://lobadk.com",
"http://localhost",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["GET"],
allow_headers=["*"],
)
extensions = (
"jpg",
"jpeg",
"png",
"webp",
"mp4",
"gif",
"mov",
"mp3",
"webm",
)
class Search(BaseModel):
search: str
class SearchResponse(BaseModel):
files: list[str]
count: int
class AppendSearch(Search):
pass
class AppendSearchResponse(BaseModel):
file: str
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
return JSONResponse(
status_code=exc.status_code,
content={"error": exc.detail},
)
@app.get("/aaaasearch/", response_model=SearchResponse)
@limiter.limit("10/minute")
async def aaaasearch(request: Request, search: Search = Depends(Search)):
try:
files = glob(f"{ABSOLUTE_PATH}*")
files = [str(Path(file).name) for file in files if search.search in file]
if len(files) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="No files found"
)
return {
"files": files,
"count": len(files),
}
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
)
@app.get("/a/", response_model=AppendSearchResponse)
@limiter.limit("10/minute")
async def a(request: Request, search: AppendSearch = Depends(AppendSearch)):
try:
files = glob(f"{ABSOLUTE_PATH}*")
files = [str(Path(file).name) for file in files if search.search in file]
if len(files) == 0:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="No files found"
)
if len(files) > 1:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail="Too many files found"
)
return {
"file": files[0],
}
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
)
def start_api():
uvicorn.run(app, host="127.0.0.1", port=8000)