从python(flask)web服务向浏览器提供文件

时间:2015-04-21 16:34:06

标签: python web-services io flask

我有一个python webservice,假设从浏览器接收GET请求,将一些数据写入csv文件并将其提供给浏览器。

我正在努力迈出最后一步。如何将文件提供回浏览器?有没有办法在不在服务器上创建或保留csv文件的情况下执行此操作?

@app.route('/', methods = ['GET'])
def get_file():

        alldata = []

        while len(new_data) > 0:
                new_data = api.timeline(max_id=oldest)
                alldata.extend(new_data)
                oldest = alldata[-1].id - 1    
        outdata = [[info.id_str] for data in alldata]

        #write the csv
        with open('data.csv', 'wb') as f:
                writer = csv.writer(f)
                writer.writerows(outdata)
        pass

if __name__ == '__main__':
  app.run(host = app.config['HOST'], port = app.config['PORT'])

1 个答案:

答案 0 :(得分:2)

不是将文件写入磁盘,而是可以像这样返回:

from flask import make_response

outdata = ""

for data in alldata:
    outdata += ",".join(data) + "\n"

response = make_response(outdata)
response.headers["Content-Disposition"] = "attachment; filename=data.csv"

return response

或者,如果您确实要将文件写入磁盘,则可以使用send_from_directory

return send_from_directory('my_app', 'data.csv')