Python HTTP 服务(推荐,支持大文件)

📅 2026/7/7 7:18:31
Python HTTP 服务(推荐,支持大文件)
跨服务器传文件一台起 HTTP 服务提供下载Server另一台作为客户端拉取Client。适用场景大文件传输Server 端被下载方# server_a.pyfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.responses import FileResponseimport osapp FastAPI()# 文件存放目录可通过 docker -v 挂载或直接设为 /path/to/your/filesFILE_DIR /app/dataapp.get(/download/{filename})def download_file(filename: str):file_path os.path.join(FILE_DIR, filename)# 安全检查防止路径穿越攻击如 ../../etc/passwdif not os.path.abspath(file_path).startswith(os.path.abspath(FILE_DIR)):raise HTTPException(status_code400, detailInvalid filename)if not os.path.exists(file_path) or not os.path.isfile(file_path):raise HTTPException(status_code404, detailFile not found)return FileResponse(file_path, filenamefilename, media_typeapplication/octet-stream)if __name__ __main__:import uvicornuvicorn.run(app, host0.0.0.0, port7011)# 启动 Server需安装 fastapi, uvicornpython3 server_a.pyClient 端下载方# client_b.pyimport requestsimport os# 替换为 Server 的 IP 和端口SERVER_A_IP 132.0.0.1PORT 7011FILENAME 要下载的文件名url fhttp://{SERVER_A_IP}:{PORT}/download/{FILENAME}save_path f./{FILENAME}print(f开始从 {url} 下载文件...)try:with requests.get(url, streamTrue, timeout3600) as response:response.raise_for_status()total_size int(response.headers.get(content-length, 0))downloaded_size 0with open(save_path, wb) as f:for chunk in response.iter_content(chunk_size8192):if chunk:f.write(chunk)downloaded_size len(chunk)if total_size 0:percent (downloaded_size / total_size) * 100print(f\r下载进度: {percent:.2f}%, end)print(f\n下载完成文件已保存至: {os.path.abspath(save_path)})except requests.exceptions.RequestException as e:print(f下载失败: {e})# 启动 Client需安装 requestspython3 client_b.py注意事项Server 和 Client 之间网络需互通同一内网或公网可达用 Docker 跑 Server可通过-p 7011:7011将容器端口绑定到物理机端口外部可通过物理机IP:端口访问容器服务文件目录用-v挂载即可方案二scp简单快捷适合小文件双方必须都有 SSH 访问权限。# 从本地推送到远程scp /path/to/local/file userremote_ip:/path/to/remote/# 从远程拉取到本地scp userremote_ip:/path/to/remote/file /path/to/local/# 递归传输目录scp -r /path/to/local/dir userremote_ip:/path/to/remote/