Norcoo commited on
Commit
c44f40c
·
verified ·
1 Parent(s): 13518fd

Upload 2 files

Browse files
Files changed (1) hide show
  1. app.py +6 -13
app.py CHANGED
@@ -11,6 +11,7 @@ import threading
11
  import time
12
  import random
13
  from fastapi.responses import FileResponse, JSONResponse
 
14
 
15
  # 环境变量
16
  ACCESS_PASSWORD = os.environ.get("ACCESS_PASSWORD", "changeme")
@@ -82,12 +83,11 @@ def generate_image_hash():
82
  return uuid.uuid4().hex[:12]
83
 
84
  def generate_full_url(image_hash):
85
- """生成完整的图片URL(使用专用API端点)"""
86
  api_path = f"/api/img/{image_hash}"
87
  if HF_USERNAME and HF_SPACE_NAME:
88
  return f"https://{HF_USERNAME}-{HF_SPACE_NAME}.hf.space{api_path}"
89
  else:
90
- # 返回相对路径,用户访问时会自动补全域名
91
  return api_path
92
 
93
  def keep_alive():
@@ -543,11 +543,11 @@ with gr.Blocks(title="My图床", theme=gr.themes.Soft(), css=custom_css) as grad
543
  # 在Gradio的底层FastAPI上添加自定义API路由
544
  @gradio_app.app.get("/api/img/{image_hash}")
545
  async def get_image(image_hash: str):
546
- """通过hash获取图片"""
547
  try:
548
  conn = get_db_connection()
549
  cursor = conn.cursor()
550
- cursor.execute("SELECT * FROM images WHERE hash = ?", (image_hash,))
551
  row = cursor.fetchone()
552
  conn.close()
553
 
@@ -565,15 +565,8 @@ async def get_image(image_hash: str):
565
  content={"error": "Image file not found"}
566
  )
567
 
568
- # 返回图片文件
569
- return FileResponse(
570
- file_path,
571
- media_type=row['mime_type'],
572
- headers={
573
- "Cache-Control": "public, max-age=31536000",
574
- "Content-Disposition": f'inline; filename="{row["original_filename"]}"'
575
- }
576
- )
577
 
578
  except Exception as e:
579
  return JSONResponse(
 
11
  import time
12
  import random
13
  from fastapi.responses import FileResponse, JSONResponse
14
+ from starlette.responses import RedirectResponse
15
 
16
  # 环境变量
17
  ACCESS_PASSWORD = os.environ.get("ACCESS_PASSWORD", "changeme")
 
83
  return uuid.uuid4().hex[:12]
84
 
85
  def generate_full_url(image_hash):
86
+ """生成完整的图片URL(使用API端点,会重定向到实际文件)"""
87
  api_path = f"/api/img/{image_hash}"
88
  if HF_USERNAME and HF_SPACE_NAME:
89
  return f"https://{HF_USERNAME}-{HF_SPACE_NAME}.hf.space{api_path}"
90
  else:
 
91
  return api_path
92
 
93
  def keep_alive():
 
543
  # 在Gradio的底层FastAPI上添加自定义API路由
544
  @gradio_app.app.get("/api/img/{image_hash}")
545
  async def get_image(image_hash: str):
546
+ """通过hash重定向到图片文件"""
547
  try:
548
  conn = get_db_connection()
549
  cursor = conn.cursor()
550
+ cursor.execute("SELECT file_path FROM images WHERE hash = ?", (image_hash,))
551
  row = cursor.fetchone()
552
  conn.close()
553
 
 
565
  content={"error": "Image file not found"}
566
  )
567
 
568
+ # 重定向到Gradio的文件服务路径
569
+ return RedirectResponse(url=f"/file={file_path}", status_code=302)
 
 
 
 
 
 
 
570
 
571
  except Exception as e:
572
  return JSONResponse(