Python과 Vue.JS를 이용한 CSV 파일 다운로드 구현

2018. 9. 18. 15:57서버 프로그래밍

Pandas를 이용하면 손쉽게 Query 실행 결과를 CSV 파일로 저장할 수 있다.

https://stackoverflow.com/questions/16923281/pandas-writing-dataframe-to-csv-file

When you are storing a DataFrame object into a csv file using the to_csv method, you probably wont be needing to store the preceding indices of each row of the DataFrame object.

You can avoid that by passing a False boolean value to index parameter.

Somewhat like:

df.to_csv(file_name, encoding='utf-8', index=False)

So if your DataFrame object is something like:

  Color  Number
0   red     22
1  blue     10

The csv file will store:

Color,Number
red,22
blue,10


그 다음에는 Flask의 send_from_directory를 이용하면 파일을 Response로 넘길 수가 있다.

http://docs.sherlockml.com/user-guide/apis/examples/flask_file_upload_download.html

import os

from flask import Flask, request, abort, jsonify, send_from_directory


UPLOAD_DIRECTORY = '/project/api_uploaded_files'

if not os.path.exists(UPLOAD_DIRECTORY):
    os.makedirs(UPLOAD_DIRECTORY)


api = Flask(__name__)


@api.route('/files/<path:path>')
def get_file(path):
    """Download a file."""
    return send_from_directory(UPLOAD_DIRECTORY, path, as_attachment=True)


마무리로 Vue.JS에서는 다음과 같이 다운로드 처리를 해주면 된다.

https://thewebtier.com/snippets/download-files-with-axios/

axios({
  url: 'http://api.dev/file-download',
  method: 'GET',
  responseType: 'blob', // important
}).then((response) => {
   const url = window.URL.createObjectURL(new Blob([response.data]));
   const link = document.createElement('a');
   link.href = url;
   link.setAttribute('download', 'file.pdf'); //or any other extension
   document.body.appendChild(link);
   link.click();
});