PythonのWebフレームワークであるFlaskを使用して、ファイルダウンロード機能を実装する方法について説明します。具体的には、Flaskの send_file()send_from_directory() 関数を使用した方法を紹介します。

Flaskの send_file() を利用する方法

send_file() 関数は、Flaskアプリが配置されたディレクトリ(デフォルトでは root_path)からの相対パスで指定したファイルをダウンロードさせる方法です。

from flask import Flask, send_file

app = Flask(__name__, static_folder=None)

@app.route('/report1/<string:report_id>', methods=['GET'])
def report1(report_id):
    downloadFileName = 'report1_' + report_id + '.xlsx'
    downloadFile = 'demo1.xlsx'
    return send_file(downloadFile, as_attachment=True, attachment_filename=downloadFileName)

Flaskの send_from_directory() を利用する方法

send_from_directory() 関数は、引数で指定したディレクトリからの相対パスでダウンロードさせるファイルを指定する方法です。

from flask import Flask, send_from_directory
import os

app = Flask(__name__, static_folder=None)
DOWNLOAD_DIR_PATH = os.getenv("DOWNLOAD_DIR_PATH")

@app.route('/report2/<string:report_id>', methods=['GET'])
def report2(report_id):
    downloadFileName = 'report2_' + report_id + '.xlsx'
    downloadFile = 'demo2.xlsx'
    return send_from_directory(DOWNLOAD_DIR_PATH, downloadFile, as_attachment=True, attachment_filename=downloadFileName)

以上、Python Flaskでファイルダウンロードを実現する方法について説明しました。これらの方法を活用して、Python Flaskでのファイルダウンロード機能の実装を進めてみてください。.

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です