2017-07-06 55 views
1

我有一個基於瓶的Web服務,我試圖將結果下載到用戶桌面的文件(通過https)。Python:如何寫入文件並下載它?

我想:當我點擊用戶界面導出按鈕

def write_results_to_file(results): 
    with open('output', 'w') as f: 
    f.write('\t'.join(results[1:]) + '\n') 

這種方法被激活。

但我得到:

<type 'exceptions.IOError'>: [Errno 13] Permission denied: 'output' 
     args = (13, 'Permission denied') 
     errno = 13 
     filename = 'output' 
     message = '' 
     strerror = 'Permission denied' 

有人能告訴我什麼,我做錯了什麼?

+0

聽起來像一個文件系統權限問題。您使用什麼操作系統?另外,您是在本地寫入文件還是將它發送迴響應中? – sakurashinken

+0

我正在嘗試在本地寫入,然後將其發送迴響應。不知道這是否正確,但 – user3407267

+0

您要在標題中指定內容類型,然後將文件發送回主體。 flask提供了send_file方法。無需寫入本地FS。 https://stackoverflow.com/questions/27337013/how-to-send-zip-files-in-the-python-flask-framework – sakurashinken

回答

2

有人能告訴我我在做什麼錯嗎?

您發佈的函數不是實際的Flask視圖函數(app.route()),因此它不完全清楚您的服務器在做什麼。

這可能是更接近你需要的代碼:

@app.route("/get_results") 
def get_results(): 
    tsv_plaintext = '' 

    # I'm assuming 'results' is a 2D array 
    for row in results: 
     tsv_plaintext += '\t'.join(row) 
     tsv_plaintext += '\n' 

    return Response(
     tsv_plaintext, 
     mimetype="text/tab-separated-values", 
     headers={"Content-disposition": 
       "attachment; filename=results.tsv"}) 

(從Flask: Download a csv file on clicking a button援助)