2015-04-22 20 views
0

當用戶輸入http://example2.com:5500/?param=x時,以下代碼會生成data.csv文件並將其提供給瀏覽器。它完全像這樣。FLASK:將文件傳送到API代理服務器後面的瀏覽器

但是,我已將其部署在API代理之後,以便用戶撥打http://example1.com/?param=x,該內部轉換爲http://example2.com:5500/?param=x

因此,不像以前那樣向瀏覽器提供data.csv,而是在瀏覽器上顯示所有data.csv內容。視圖源代碼功能準確顯示data.csv應該包含的內容,不包含任何HTML標頭,僅包含data.csv內容,但不作爲附件提供。有任何想法嗎?

from flask import make_response 

@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 = "" 
    for data in alldata: 
      outdata += ",".join(data) + "\n" 

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

    return response 


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

編輯:包括映射代碼轉換請求example1.com到example2.com(secret_url)

# This is example1.com 
@app.route("/api/<projectTitle>/<path:urlSuffix>", methods=['GET']) 
def projectTitlePage(projectTitle, urlSuffix): 

    projectId = databaseFunctions.getTitleProjectId(projectTitle) 
    projectInfo = databaseFunctions.getProjectInfo(projectId) 
    redirectionQueryString = re.sub('apikey=[^&]+&?', '', request.query_string).rstrip('&') 
    redirectionUrl = projectInfo['secretUrl'].rstrip('/') 
    if urlSuffix is not None: 
     redirectionUrl += '/' + urlSuffix.rstrip('/') 
    redirectionUrl += '/?' + redirectionQueryString 
    redirectionHeaders = request.headers 

    print request.args.to_dict(flat=False) 
    try: 
     r = requests.get(redirectionUrl, data=request.args.to_dict(flat=False), headers=redirectionHeaders) 
    except Exception, e: 
     return '/error=Error: bad secret url: ' + projectInfo.get('secretUrl') 

    return r.text 
+0

代理服務器必須修改響應頭文件。您可以將應用程序的HTTP響應與您在瀏覽器的調試器中從代理獲得的響應進行比較。這應該讓你知道問題出在哪裏。 – Miguel

+0

是Miguel,我從代理獲得的HTTP響應根本沒有標頭。這就像試圖從瀏覽器打開data.csv一樣。 – Arturo

+0

這是什麼代理服務器? – Miguel

回答

1

你的自產自銷的代理沒有返回頭返回給應用程序。試試這個:

@app.route("/api/<projectTitle>/<path:urlSuffix>", methods=['GET']) 
def projectTitlePage(projectTitle, urlSuffix): 

    # ... 

    return r.text, r.status_code, r.headers 
相關問題