5
사용자가 작업에 의해 정의 된 데이터로 CSV 파일을 다운로드 할 수있게하려고합니다. 파일이 존재하지 않으며 동적으로 생성됩니다. 어떻게하면 플라스크에서 이것을 할 수 있습니까?플라스크 (Flask)보기에서 CSV 파일을 만들고 다운로드하십시오.
사용자가 작업에 의해 정의 된 데이터로 CSV 파일을 다운로드 할 수있게하려고합니다. 파일이 존재하지 않으며 동적으로 생성됩니다. 어떻게하면 플라스크에서 이것을 할 수 있습니까?플라스크 (Flask)보기에서 CSV 파일을 만들고 다운로드하십시오.
csv.writer
및 stream the response으로 데이터를 생성하십시오. 중간 파일을 생성하는 대신 메모리 내 버퍼에 쓰려면 StringIO을 사용하십시오.
다음은이 작업을 수행하는 간단한 예입니다.
import csv
from datetime import datetime
from cstringio import StringIO
from flask import Flask, stream_with_context
from werkzeug.datastructures import Headers
from werkzeug.wrappers import Response
app = Flask(__name__)
# example data, this could come from wherever you are storing logs
log = [
('login', datetime(2015, 1, 10, 5, 30)),
('deposit', datetime(2015, 1, 10, 5, 35)),
('order', datetime(2015, 1, 10, 5, 50)),
('withdraw', datetime(2015, 1, 10, 6, 10)),
('logout', datetime(2015, 1, 10, 6, 15))
]
@app.route('/')
def download_log():
def generate():
data = StringIO()
w = csv.writer(data)
# write header
w.writerow(('action', 'timestamp'))
yield data.getvalue()
data.seek(0)
data.truncate(0)
# write each log item
for item in log:
w.writerow((
item[0],
item[1].isoformat() # format datetime as string
))
yield data.getvalue()
data.seek(0)
data.truncate(0)
# add a filename
headers = Headers()
headers.set('Content-Disposition', 'attachment', filename='log.csv')
# stream the response as the data is generated
return Response(
stream_with_context(generate()),
mimetype='text/csv', headers=headers
)
app.run()
'response.headers [ 'Content-Disposition'] = '첨부 파일; filename = "download.csv" ''도 작동합니다. –
@ DaveW.Smith'headers.add'와''headers.set' (http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.Headers.set)에 대한 좋은 점은 고유 한 파일 이름을 생성 할 수 있으며 Werkzeug는 헤더를 올바르게 형식화합니다. 항목을 직접 설정할 수 있다는 사실은'dict' 하위 클래스 인'headers'의 부작용이지만 헤더를 사용하는 최선의 방법은 아닙니다. – davidism