ZHIWEI666 commited on
Commit
0dc0010
·
verified ·
1 Parent(s): 48ca787

Upload api_share.py

Browse files
Files changed (1) hide show
  1. api_share.py +25 -11
api_share.py CHANGED
@@ -6,7 +6,7 @@ from datetime import datetime
6
  from fastapi import APIRouter, UploadFile, File, Form
7
  from fastapi.responses import FileResponse
8
  from huggingface_hub import hf_hub_download, upload_file
9
- from core import get_db_list, save_db, api, REPO_ID, TOKEN, ShareLikeReq, ShareCommentReq, ShareCommentActionReq, ShareEditReq, ShareDeleteReq
10
 
11
  router = APIRouter()
12
 
@@ -17,7 +17,6 @@ async def get_share_list():
17
  @router.get("/api/share/image")
18
  async def get_share_image(name: str):
19
  try:
20
- # 🌟 优化:将下载图片操作放入线程池,防止阻塞主事件循环
21
  path = await asyncio.to_thread(hf_hub_download, repo_id=REPO_ID, filename=f"community_images/{name}", repo_type="dataset", token=TOKEN)
22
  return FileResponse(path)
23
  except: return {"status": "error"}
@@ -26,7 +25,7 @@ async def get_share_image(name: str):
26
  async def publish_share(username: str = Form(...), title: str = Form(...), content: str = Form(...), image: UploadFile = File(None)):
27
  try:
28
  db = get_db_list("community_posts.json")
29
- post_id = uuid.uuid4().hex # 🌟 优化:使用完整 32 位 UUID 防碰撞
30
  post_data = { "id": post_id, "author": username, "title": title[:20], "content": content, "time": int(time.time() * 1000), "likes": 0, "liked_by": [], "comments": [] }
31
 
32
  if image and image.filename:
@@ -34,25 +33,41 @@ async def publish_share(username: str = Form(...), title: str = Form(...), conte
34
  image_name = f"{post_id}{ext}"
35
  temp_path = f"temp_share_{uuid.uuid4().hex}{ext}"
36
  with open(temp_path, "wb") as f: f.write(await image.read())
37
- # 🌟 优化:将上传图片操作放入线程池,防止假死
38
  await asyncio.to_thread(upload_file, path_or_fileobj=temp_path, path_in_repo=f"community_images/{image_name}", repo_id=REPO_ID, repo_type="dataset", token=TOKEN)
39
  if os.path.exists(temp_path): os.remove(temp_path)
40
  post_data["image"] = image_name
41
 
42
  db.insert(0, post_data)
43
- save_db(db, "community_posts.json") # 瞬间落入内存字典
44
  return {"status": "success", "post": post_data}
45
  except Exception as e: return {"status": "error", "message": str(e)}
46
 
 
47
  @router.post("/api/share/edit")
48
- async def edit_share(req: ShareEditReq):
49
  try:
50
  db = get_db_list("community_posts.json")
51
  for p in db:
52
- if p["id"] == req.post_id:
53
- if p["author"] != req.username: return {"status": "error", "message": "无权限"}
54
- p["title"] = req.title[:20]
55
- p["content"] = req.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  save_db(db, "community_posts.json")
57
  return {"status": "success"}
58
  return {"status": "error", "message": "帖子不存在"}
@@ -68,7 +83,6 @@ async def delete_share(req: ShareDeleteReq):
68
  del_post = db.pop(i)
69
  if del_post.get("image"):
70
  try:
71
- # 🌟 优化:后台丢入线程池静默删除垃圾图片,不让用户等待
72
  asyncio.create_task(asyncio.to_thread(api.delete_file, path_in_repo=f"community_images/{del_post['image']}", repo_id=REPO_ID, token=TOKEN))
73
  except: pass
74
  save_db(db, "community_posts.json")
 
6
  from fastapi import APIRouter, UploadFile, File, Form
7
  from fastapi.responses import FileResponse
8
  from huggingface_hub import hf_hub_download, upload_file
9
+ from core import get_db_list, save_db, api, REPO_ID, TOKEN, ShareLikeReq, ShareCommentReq, ShareCommentActionReq, ShareDeleteReq
10
 
11
  router = APIRouter()
12
 
 
17
  @router.get("/api/share/image")
18
  async def get_share_image(name: str):
19
  try:
 
20
  path = await asyncio.to_thread(hf_hub_download, repo_id=REPO_ID, filename=f"community_images/{name}", repo_type="dataset", token=TOKEN)
21
  return FileResponse(path)
22
  except: return {"status": "error"}
 
25
  async def publish_share(username: str = Form(...), title: str = Form(...), content: str = Form(...), image: UploadFile = File(None)):
26
  try:
27
  db = get_db_list("community_posts.json")
28
+ post_id = uuid.uuid4().hex
29
  post_data = { "id": post_id, "author": username, "title": title[:20], "content": content, "time": int(time.time() * 1000), "likes": 0, "liked_by": [], "comments": [] }
30
 
31
  if image and image.filename:
 
33
  image_name = f"{post_id}{ext}"
34
  temp_path = f"temp_share_{uuid.uuid4().hex}{ext}"
35
  with open(temp_path, "wb") as f: f.write(await image.read())
 
36
  await asyncio.to_thread(upload_file, path_or_fileobj=temp_path, path_in_repo=f"community_images/{image_name}", repo_id=REPO_ID, repo_type="dataset", token=TOKEN)
37
  if os.path.exists(temp_path): os.remove(temp_path)
38
  post_data["image"] = image_name
39
 
40
  db.insert(0, post_data)
41
+ save_db(db, "community_posts.json")
42
  return {"status": "success", "post": post_data}
43
  except Exception as e: return {"status": "error", "message": str(e)}
44
 
45
+ # 🌟 核心升级:编辑接口重构,支持表单图片修改
46
  @router.post("/api/share/edit")
47
+ async def edit_share(post_id: str = Form(...), username: str = Form(...), title: str = Form(...), content: str = Form(...), image: UploadFile = File(None)):
48
  try:
49
  db = get_db_list("community_posts.json")
50
  for p in db:
51
+ if p["id"] == post_id:
52
+ if p["author"] != username: return {"status": "error", "message": "无权限"}
53
+ p["title"] = title[:20]
54
+ p["content"] = content
55
+ p["last_edit_date"] = datetime.now().strftime("%Y-%m-%d")
56
+
57
+ # 如果上传了新图片,删除老图并上传新图
58
+ if image and image.filename:
59
+ ext = os.path.splitext(image.filename)[1].lower()
60
+ image_name = f"{post_id}_{uuid.uuid4().hex[:8]}{ext}"
61
+ temp_path = f"temp_share_edit_{uuid.uuid4().hex}{ext}"
62
+ with open(temp_path, "wb") as f: f.write(await image.read())
63
+ await asyncio.to_thread(upload_file, path_or_fileobj=temp_path, path_in_repo=f"community_images/{image_name}", repo_id=REPO_ID, repo_type="dataset", token=TOKEN)
64
+ if os.path.exists(temp_path): os.remove(temp_path)
65
+
66
+ if p.get("image"):
67
+ try: asyncio.create_task(asyncio.to_thread(api.delete_file, path_in_repo=f"community_images/{p['image']}", repo_id=REPO_ID, token=TOKEN))
68
+ except: pass
69
+ p["image"] = image_name
70
+
71
  save_db(db, "community_posts.json")
72
  return {"status": "success"}
73
  return {"status": "error", "message": "帖子不存在"}
 
83
  del_post = db.pop(i)
84
  if del_post.get("image"):
85
  try:
 
86
  asyncio.create_task(asyncio.to_thread(api.delete_file, path_in_repo=f"community_images/{del_post['image']}", repo_id=REPO_ID, token=TOKEN))
87
  except: pass
88
  save_db(db, "community_posts.json")