Python/Flask实现提供测试文件下载,可自定义文件大小

2020-12-26 2043点热度 0人点赞 1条评论

为了测试服务器速度,有时候需要提供下载文件,这里写了一段Python代码,可提供下载测试文件、还可以让客户端请求的时候自定义下载文件的大小,这样省去找一个固定大小的文件丢到服务器上的麻烦了。

download_test.py
from flask import Flask, request, Response
from datetime import datetime

app = Flask(__name__)


@app.route("/")
def index():
    return "Hello World!"


@app.route("/ping")
def ping():
    now_time = datetime.now().strftime('%Y-%m-%d %A %H:%M:%S') + ' ' + datetime.now().astimezone().strftime('%z')
    return "Time: " + now_time + "<br/><br/>" + str(request.headers).replace("\n", "<br/>")


@app.route("/ping/download")
def ping_download():
    # file length in mb
    flimb = request.args.get("flimb")
    file_length = int(flimb) * 1024 * 1024

    def generate():
        resp_length = 0
        while resp_length < file_length:
            chunk_length = 8192
            if resp_length + 8192 > file_length:
                chunk_length = file_length - resp_length
            chunk = bytes(chunk_length)
            resp_length += 8192
            yield chunk

    response = Response(generate(), content_type='application/octet-stream')
    response.headers['Content-Disposition'] = 'attachment;filename=test_download_file_%s.dat' % sizeof_fmt(file_length)
    response.headers['Content-Length'] = '%d' % file_length
    return response


def sizeof_fmt(num, suffix='B'):
    for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)

Java、JSP版本请看这里:https://blog.terrynow.com/2020/12/25/java-jsp-download-test-server/

admin

这个人很懒,什么都没留下

文章评论

  • Asepaloupe

    Absolutely with you it agree. I think, what is it excellent idea.

    2022-03-09
  • 您需要 登录 之后才可以评论