2017-10-17 72 views
0

這個燒瓶應用程序的目標是填充表單,解析生成表單的數據,啓動構建,壓縮並將此構建發送給用戶。如何渲染模板並同時用燒瓶發送文件

一切工作正常,但我希望一旦表格被填充,用戶被重定向到一個等待頁面,如果這當然是可能的。

這是我的時刻代碼:

def create_and_download_build(form) 
     # Some parsing in the beginning of the function, the build etc... 
     os.system('tar -zcvf build.tar.gz dist/') 
     headers = {"Content-Disposition": "attachment; filename=build.tar.gz"} 
     with open('build.tar.gz', 'r+b') as data_file: 
      data = data_file.read() 
     response = make_response(render_template('waiting.html'), (data, headers)) 
     return response 

這是這個函數聲明,在我_init__.py:

@app.route('/', methods=('GET', 'POST')) 
    def index(): 
     form = MyForm() # MyForm is a class in which there is some 
         # wtform field (for example TextField) 
     if form.validate_on_submit(): # This is called once the form is validated 
      return create_and_download_build(request.form) 
     return render_template('index.html', form=form) 

它不工作,我收到此錯誤在我稱之爲make_response行: AttributeError: 'tuple' object has no attribute 'decode'

如果我改變make_response到:response = make_response((data, headers)),它會正確地上傳文件,但它不會渲染waiting.html頁面。
同樣,如果我將其更改爲:response = make_response(render_template('waiting.html')),它將呈現模板,但不會下載該文件。

是否有一種方法可以執行這兩種操作?

回答

2

簡答:不可以。顯然,您不能一次返回不同的回覆。

快速和骯髒的解決方案將返回您的「waiting.html」模板的HTML響應,並從此模板添加一些JavaScript來啓動下載。

注意,這與燒瓶無關,你會有任何服務器端語言/技術的相同行爲。這就是HTTP的工作原理。