-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
134 lines (103 loc) · 3.37 KB
/
Copy pathmain.py
File metadata and controls
134 lines (103 loc) · 3.37 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import os
import random
from fastapi import FastAPI, Request, Response
from fastapi.responses import FileResponse, JSONResponse
from PIL import Image
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(
title="CatMemesAPI",
version="1.2.0",
description="API with memes about cats"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
MEMES_DIR = "memes"
def load_memes():
"""Загружает все мемы из папки и парсит ID из имени файла."""
memes = []
if not os.path.exists(MEMES_DIR):
return memes
for f in os.listdir(MEMES_DIR):
if f.lower().endswith(('.jpg')):
try:
name_parts = f.replace('.jpg', '')
meme_id = int(name_parts.replace('meme_cat_', ''))
except (ValueError, IndexError):
meme_id = len(memes)
memes.append({"id": meme_id, "filename": f})
memes.sort(key=lambda x: x['id'])
return memes
memes = load_memes()
@app.get("/")
def info():
"""Информация об API."""
return {
"title": "CatMemesAPI",
"version": "1.2.0",
"total_memes": len(memes),
"formats": ["jpg"],
"endpoints": {
"/": "API info",
"/meme/search?limit=5": "Get 5 random memes",
"/meme/{meme_id}": "Get meme by ID"
},
"docs": "https://catmemesapi.onrender.com/docs"
}
@app.get("/meme/search")
def search_memes(request: Request, limit: int = 1):
"""Возвращает случайные мемы."""
if not memes:
return JSONResponse(status_code=404, content={"error": "No memes found"})
limit = min(limit, len(memes))
selected = random.sample(memes, limit)
result = []
for m in selected:
filepath = os.path.join(MEMES_DIR, m['filename'])
try:
with Image.open(filepath) as img:
width, height = img.size
except Exception:
width, height = 0, 0
full_url = str(request.url_for("get_meme_by_id", meme_id=m["id"]))
result.append({
"id": m["id"],
"url": full_url,
"width": width,
"height": height
})
return result
@app.get("/meme/{meme_id}")
def get_meme_by_id(meme_id: int):
"""Возвращает мем по ID."""
for m in memes:
if m["id"] == meme_id:
filepath = os.path.join(MEMES_DIR, m['filename'])
if os.path.exists(filepath):
return FileResponse(filepath)
return JSONResponse(status_code=404, content={"error": "File not found"})
return JSONResponse(status_code=404, content={"error": "Meme not found"})
@app.get("/health")
def health():
return {"status": "ok"}
@app.head("/")
def info_head():
return Response()
@app.head("/meme/search")
def search_memes_head():
return Response()
@app.head("/meme/{meme_id}")
def get_meme_by_id_head(meme_id: int):
"""HEAD-запрос для проверки существования мема."""
for m in memes:
if m["id"] == meme_id:
filepath = os.path.join(MEMES_DIR, m['filename'])
if os.path.exists(filepath):
return Response()
return Response(status_code=404)
@app.head("/health")
def health_head():
return Response()