write a python picture gallery fastapi
时间: 2024-09-11 20:12:27 浏览: 46
在Python中创建一个快速API图片画廊,我们可以使用FastAPI作为Web框架,Uvicorn作为服务器,以及像`Pillow`库处理图像,`pathlib`管理文件路径,`sqlite3`存储图片信息。以下是一个简单的示例:
首先安装所需的库:
```bash
pip install fastapi uvicorn pillow sqlalchemy
```
然后创建一个`main.py`文件,包含以下几个部分:
```python
from fastapi import FastAPI, File, UploadFile
import os
from PIL import Image
from io import BytesIO
from starlette.responses import StreamingResponse
from sqlalchemy import create_engine, Column, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 初始化数据库
Base = declarative_base()
engine = create_engine('sqlite:///images_gallery.db')
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# 数据模型
class ImageGallery(Base):
__tablename__ = "image_gallery"
id = Column(Integer, primary_key=True)
filename = Column(String, unique=True)
description = Column(Text)
# API配置
app = FastAPI()
@app.on_event("startup")
async def startup():
Base.metadata.create_all(bind=engine)
@app.post("/upload-image/")
async def upload_image(file: UploadFile = File(...)):
# 检查文件类型和大小
if file.content_type not in ["image/jpeg", "image/png"]:
return {"error": "Invalid image format"}
if file.size > 4 * 1024 * 1024: # 限制最大4MB
return {"error": "Image size exceeds limit"}
try:
# 保存图片到临时目录,并获取描述信息
temp_path = await save_temp_image(file.file)
description = await get_description_from_user(temp_path) # 这里假设有一个函数从用户输入获取描述
# 添加到数据库
with SessionLocal() as session:
new_image = ImageGallery(filename=file.filename, description=description)
session.add(new_image)
session.commit()
return {"message": f"Image '{file.filename}' uploaded successfully."}
except Exception as e:
return {"error": str(e)}
async def save_temp_image(image_bytes):
temp_file = BytesIO()
temp_file.write(image_bytes)
temp_file.seek(0)
img = Image.open(temp_file)
temp_path = "temp/" + file.filename
img.save(temp_path)
return temp_path
def get_description_from_user(path): # 这里需要实现一个实际的交互或API请求获取用户描述
# 示例:return input("Please describe the image: ")
pass
@app.get("/{filename}")
async def serve_image(filename: str):
try:
with open(os.path.join("temp", filename), 'rb') as image_file:
response = StreamingResponse(image_file, media_type="image/jpeg")
response.headers["Content-Disposition"] = f"attachment; filename={filename}"
return response
except FileNotFoundError:
return {"error": "Image not found"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
```
这个例子展示了基本的图片上传、存储(暂存于本地),以及根据ID返回图片的功能。注意这只是一个基础模板,实际应用可能需要更完善的错误处理和前端界面。
阅读全文