烧瓶send_file不会返回文件

时间:2020-08-27 07:10:01

标签: python python-3.x flask

我正试图通过app.py发送由服务模块即时生成的文件。显然,flask的send_file方法不会返回任何内容。

返回所述文件的方法:

@app.route("/build", methods=['POST'])
def build():
   global prev
   if(request.method == 'POST'):
       Data = request.form.getlist('Data[]')
       project_count = request.form.get("projectCount")
       testi_count = request.form.get("testiCount")
       temp = service.update_pf(Data, project_count, testi_count)
       try:
           os.remove(prev)
       except:
           print("Cleanup failed", prev)
       prev = temp+".zip"
       return send_file(temp+".zip", as_attachment=True)

有关该功能的所有其他操作,包括清理操作。而且我无法将任何文件发送到前端,而不仅仅是zip文件。

控制台输出:

* Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 240-525-557
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Cleanup failed
yavixux.zip
127.0.0.1 - - [27/Aug/2020 12:36:55] "[37mPOST /build HTTP/1.1[0m" 200 -
jun.zip
127.0.0.1 - - [27/Aug/2020 12:36:59] "[37mPOST /build HTTP/1.1[0m" 200 -

不要介意清理失败。应该的。

我使用Python3,前端是Google Chrome V84

1 个答案:

答案 0 :(得分:0)

CSV路径:

@app.route("/get-csv/<csv_id>")
def get_csv(csv_id):
    filename = f"{csv_id}.csv"

    try:
        return send_from_directory(app.config["CLIENT_CSV"], filename=filename, as_attachment=True)
    except FileNotFoundError:
        abort(404)

PDF路线:

@app.route("/get-pdf/<pdf_id>")
def get_pdf(pdf_id):

    filename = f"{pdf_id}.csv"

    try:
        return send_from_directory(app.config["CLIENT_PDF"], filename=filename, as_attachment=True)
    except FileNotFoundError:
        abort(404)

发送文件并安全加入:

@app.route("/get-csv/<path:filename>")    
def get_csv(filename):

    safe_path = safe_join(app.config["CLIENT_CSV"], filename)

    try:
        return send_file(safe_path, as_attachment=True)
    except FileNotFoundError:
       abort(404)

有关更多信息,请参阅 https://pythonise.com/series/learning-flask/sending-files-with-flask