Files
full-stack-doc/backend/debug_download_detailed.py
2025-10-14 20:05:29 +08:00

150 lines
4.8 KiB
Python

#!/usr/bin/env python3
"""
详细调试下载接口的每个步骤
"""
import requests
import os
import mysql.connector
def debug_download_step_by_step():
"""逐步调试下载过程"""
print("=== 详细下载接口调试 ===")
# 测试参数
user_id = 3
file_id = 22
print(f"测试参数: user_id={user_id}, file_id={file_id}")
# 步骤1: 检查数据库中的文件记录
print("\n--- 步骤1: 检查数据库记录 ---")
try:
conn = mysql.connector.connect(
host='101.126.85.76',
user='mytest_db',
password='mytest_db',
database='mytest_db'
)
cursor = conn.cursor()
cursor.execute('''
SELECT id, user_id, original_filename, filename, file_path, file_size, mime_type
FROM files
WHERE id = %s AND user_id = %s
''', (file_id, user_id))
file_record = cursor.fetchone()
if file_record:
id, db_user_id, original_filename, filename, file_path, file_size, mime_type = file_record
print(f"✅ 数据库记录找到:")
print(f" 文件ID: {id}")
print(f" 用户ID: {db_user_id}")
print(f" 原始文件名: {original_filename}")
print(f" 存储文件名: {filename}")
print(f" 文件路径: {file_path}")
print(f" 文件大小: {file_size} bytes")
print(f" MIME类型: {mime_type}")
else:
print("❌ 数据库中没有找到匹配的记录")
return
cursor.close()
conn.close()
except Exception as e:
print(f"❌ 数据库查询失败: {e}")
return
# 步骤2: 检查实际文件是否存在
print("\n--- 步骤2: 检查实际文件 ---")
if os.path.exists(file_path):
actual_size = os.path.getsize(file_path)
print(f"✅ 文件存在:")
print(f" 路径: {os.path.abspath(file_path)}")
print(f" 实际大小: {actual_size} bytes")
if actual_size == file_size:
print("✅ 文件大小匹配数据库记录")
else:
print(f"⚠️ 文件大小不匹配: 数据库{file_size} vs 实际{actual_size}")
# 检查文件可读性
if os.access(file_path, os.R_OK):
print("✅ 文件可读")
# 读取文件内容验证
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
print(f"✅ 文件内容可读,长度: {len(content)} 字符")
print(f" 内容预览: {content[:50]}...")
except Exception as e:
print(f"❌ 读取文件内容失败: {e}")
else:
print("❌ 文件不可读 - 权限问题")
else:
print(f"❌ 文件不存在: {file_path}")
return
# 步骤3: 测试API下载请求
print("\n--- 步骤3: 测试API下载请求 ---")
try:
download_data = {'user_id': user_id, 'file_id': file_id}
print(f"发送请求: POST /api/v1/files/download")
print(f"请求体: {download_data}")
response = requests.post(
'http://localhost:8000/api/v1/files/download',
json=download_data,
timeout=10
)
print(f"响应状态码: {response.status_code}")
print(f"响应头: {dict(response.headers)}")
if response.status_code == 200:
print("✅ 下载成功!")
content_type = response.headers.get('content-type', '')
content_length = len(response.content)
print(f" 响应类型: {content_type}")
print(f" 内容长度: {content_length} bytes")
if content_type.startswith('text/'):
text_content = response.text
print(f" 文本内容长度: {len(text_content)} 字符")
print(f" 文本内容预览: {text_content[:50]}...")
# 验证内容
if len(text_content) == file_size / 2: # 大约UTF-8字符数
print("✅ 内容大小预期范围内")
else:
print(f"⚠️ 内容大小异常: 预期~{file_size//2}字符,实际{len(text_content)}字符")
else:
print(" 二进制内容,无法显示预览")
else:
print("❌ 下载失败!")
print(f"错误响应: {response.text}")
# 尝试解析JSON错误
try:
error_data = response.json()
print(f"错误详情: {error_data}")
except:
print("无法解析错误响应")
except Exception as e:
print(f"❌ API请求失败: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
debug_download_step_by_step()