Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 46 additions & 2 deletions app/api/v1/endpoints/auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from fastapi import APIRouter, HTTPException, Depends
from fastapi import APIRouter, HTTPException, Depends, UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from passlib.context import CryptContext
from datetime import datetime, timedelta
Expand All @@ -17,6 +17,10 @@
from app.utils.get_db import get_db
from app.utils.redis import get_redis_client
from app.curd.note import find_recent_notes_in_db
from fastapi import File, UploadFile
from fastapi.responses import FileResponse
import os
from uuid import uuid4

router = APIRouter()

Expand Down Expand Up @@ -159,4 +163,44 @@ async def get_recent_notes(db: AsyncSession = Depends(get_db)):
notes = await find_recent_notes_in_db(db)
return {
"notes": notes
}
}

# 上传图片接口
@router.post("/image/upload", response_model=dict)
async def upload_image(image: UploadFile = File(...)):
"""
上传图片接口
"""
try:
# 生成唯一文件名
file_extension = os.path.splitext(image.filename)[1]
unique_filename = f"{uuid4()}{file_extension}"
image_path = os.path.join("/lhcos-data/images", unique_filename)

# 确保以二进制模式写入文件,避免编码问题
with open(image_path, "wb") as f:
f.write(await image.read())

# # 生成 URL 路径
image_url = f"/images/{unique_filename}"

return {"image_url": image_url}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))


@router.get("/image/{imgname}", response_model=dict)
async def get_image(imgname: str):
"""
获取图片接口
"""
try:
image_path = os.path.join("/lhcos-data/images", imgname)
if not os.path.exists(image_path):
raise HTTPException(status_code=404, detail="Image not found")
return FileResponse(
path=image_path,
media_type="image/png" # 根据实际图片类型修改或动态设置
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
2 changes: 1 addition & 1 deletion app/curd/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ async def get_user_by_email(db: AsyncSession, email: str):
return result.scalar_one_or_none()

async def create_user(db: AsyncSession, email: str, username: str, hashed_password: str):
new_user = User(email=email, username=username, password=hashed_password, avatar="/static/avatar/default.png")
new_user = User(email=email, username=username, password=hashed_password, avatar="/lhcos-data/avatar/default.png")
db.add(new_user)
await db.commit()
await db.refresh(new_user)
Expand Down
21 changes: 20 additions & 1 deletion app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from loguru import logger
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import os

app = FastAPI()

Expand Down Expand Up @@ -40,5 +41,23 @@ async def log_requests(request: Request, call_next):
allow_headers=["*"], # 允许的请求头
)

from pathlib import Path
is_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"

if is_github_actions:
# GitHub Actions 环境 - 使用项目内临时目录
BASE_DIR = Path(__file__).resolve().parent.parent
AVATAR_DIR = os.path.join(BASE_DIR, "static", "avatar")
IMAGES_DIR = os.path.join(BASE_DIR, "static", "images")
else:
# 生产环境 - 使用实际云存储目录
AVATAR_DIR = "/lhcos-data/avatar"
IMAGES_DIR = "/lhcos-data/images"

# 确保目录存在
os.makedirs(AVATAR_DIR, exist_ok=True)
os.makedirs(IMAGES_DIR, exist_ok=True)

# 挂载静态文件目录
app.mount("/static", StaticFiles(directory="app/static"), name="static")
app.mount("/avatar", StaticFiles(directory=AVATAR_DIR), name="avatar")
app.mount("/images", StaticFiles(directory=IMAGES_DIR), name="images")
Binary file modified requirements.txt
Binary file not shown.