python使用flask发送文件(xlsx)

2020-06-06  本文已影响0人  Odven

这个程序主要是从有规律的目录中下载xlsx文件

目录结构

flask_test.py
plan
    2020-06-01
        2020_06_01-name.xlsx
        ....
    2020-06-02
        2020_06_02-name.xlsx
        ....

flask_test.py

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

import os
from flask import Flask, request, send_file, send_from_directory, jsonify

app = Flask(__name__)

@app.route("/api/show_files", methods=["GET"])
def show_file():
    d = request.args.get("date", "")
    print(d)
    d = "plan" + os.sep + d
    print(d)

    f_list = list()
    for base, dir, file_list in os.walk(d):
        for file in file_list:
            f_list.append(file)

    # 返回目录路径下面的文件
    return '{"data": %s}' % f_list, 200, {"Content-Type": "application/json"}  


@app.route("/api/get_file", methods=["GET", "POST"])
def get_file():
    if request.method == "POST":
        f = request.form.get("file", "")
        print(f)

        try:
            d = f.split("-")[0]
            y, m, d = d.split("_")
        except Exception as e:
            return "文件格式不正确等"

        dir_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "plan" + os.sep + "%s-%s-%s" % (y, m, d))  # 拼接目录路径

        file_path = dir_path + os.sep + f  # 拼接文件位置
        print(file_path)
        if not os.path.exists(file_path):
            return "文件不存在"

        # return send_file(file_path, attachment_filename="%s" % f, as_attachment=True)

        return send_from_directory(dir_path, f, as_attachment=True)

    return '''
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Download file</title>
    </head>
    <body>
        <form action="/api/show_files" method="get">
            选择年月日查看目录下的文件列表: <input type="date" name="date" required="required">
            <input type="submit">
        </form>
        <hr>
        <form action="/api/get_file" method="post">
            文件名: <input type="text" name="file" required="required">
            <input type="submit">
        </form>
    </body>
    </html>
    '''

@app.errorhandler(404)
def error_404(error):
    return "迷失在外太空<br> ERROR --> %s" % error, 404


if __name__ == '__main__':
    app.run(debug=True)

浏览器输入: 127.0.0.1:5000/api/get_file

上一篇下一篇

猜你喜欢

热点阅读