chore: update
This commit is contained in:
@@ -1,35 +1,34 @@
|
||||
import os
|
||||
import shutil
|
||||
from fastapi import FastAPI, File, UploadFile, HTTPException
|
||||
from fastapi.responses import FileResponse
|
||||
from pathlib import Path
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
# Thư mục lưu trữ ảnh (nên được mount volume khi chạy docker)
|
||||
STORAGE_DIR = Path("images")
|
||||
STORAGE_DIR.mkdir(exist_ok=True)
|
||||
|
||||
@app.post("/")
|
||||
async def upload_image(file: UploadFile = File(...)):
|
||||
# Chỉ chấp nhận định dạng ảnh
|
||||
if not file.content_type.startswith("image/"):
|
||||
raise HTTPException(status_code=400, detail="File không hợp lệ. Chỉ chấp nhận ảnh.")
|
||||
raise HTTPException(status_code=400, detail="Chỉ chấp nhận file ảnh.")
|
||||
|
||||
file_path = STORAGE_DIR / file.filename
|
||||
|
||||
# Ghi file theo block để tối ưu bộ nhớ
|
||||
with open(file_path, "wb") as f:
|
||||
content = await file.read()
|
||||
f.write(content)
|
||||
# Ghi file theo kiểu stream để tránh tràn RAM
|
||||
try:
|
||||
with file_path.open("wb") as buffer:
|
||||
shutil.copyfileobj(file.file, buffer)
|
||||
finally:
|
||||
file.file.close()
|
||||
|
||||
return {"status": "success", "filename": file.filename}
|
||||
|
||||
@app.get("/{name}")
|
||||
async def get_image(name: str):
|
||||
file_path = STORAGE_DIR / name
|
||||
|
||||
if not file_path.exists() or not file_path.is_file():
|
||||
raise HTTPException(status_code=404, detail="Không tìm thấy ảnh")
|
||||
|
||||
# Trả về ảnh trực tiếp cho trình duyệt/client
|
||||
return FileResponse(file_path)
|
||||
+4
-4
@@ -20,11 +20,11 @@ spec:
|
||||
- containerPort: 8080
|
||||
resources:
|
||||
requests:
|
||||
memory: "32Mi"
|
||||
cpu: "50m"
|
||||
memory: "128Mi"
|
||||
cpu: "150m"
|
||||
limits:
|
||||
memory: "64Mi"
|
||||
cpu: "250m"
|
||||
memory: "512Mi"
|
||||
cpu: "450m"
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
|
||||
Reference in New Issue
Block a user