开启高性能下载web服务

重要更新见最下头!!!

问题

想高性能传输文件, 安装了python3.6以上, 如果能开启一个高性能的web来传输文件就好了

步骤

安装python3

安装依赖 pip3 install fastapi aiofiles uvicorn

编写web.py保存

访问 http://127.0.0.1:8002/d/files.txt 即可

# save in web.py
# python >= 3.6
# pip install aiofiles fastapi uvicorn
import os

import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse



app = FastAPI()

@app.get("/d/{p:path}")
async def download(p: str):
    if not os.path.exists(p):
        raise HTTPException(status_code=404, detail={"reason": f"{p}不存在","dir": os.path.abspath('.'), "files": os.listdir()})
    if not os.path.isfile(p):
        raise HTTPException(status_code=400, detail={"reason": f"{p}不是文件", "dir": os.path.abspath(p), "files": os.listdir(p)})
    return FileResponse(p)
if __name__ == '__main__':
    uvicorn.run("web:app", host='0.0.0.0', port=8002, reload=True)

2021.09.26更新!!!

我用go实现的比较简陋,现在已经有了更好的实现,是用rust实现的,性能更好,包又小,功能还更全。强烈推荐:

svenstaro/miniserve: 🌟 For when you really just want to serve some files over HTTP right now! (github.com)

次博客仍然保留,仅做学习交流使用,实际使用更推荐miniserve