FLASK:将文件提供给 API 代理后的浏览器

FLASK: Serving file to browser behind API proxy

当用户输入 http://example2.com:5500/?param=x 时,下面的代码会生成一个 data.csv 文件并将其提供给浏览器。它像这样完美地工作。

但是,我已将其部署在 API 代理后面,以便用户调用 http://example1.com/?param=x 并在内部转换为 http://example2.com:5500/?param=x.

因此,它不再像以前那样向浏览器提供 data.csv,而是在浏览器上显示所有 data.csv 内容。视图 source-code 功能准确显示了 data.csv 应该包含的内容,没有任何 HTML headers,只有 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

您的本地代理未将 headers 返回给应用程序。试试这个:

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

    # ...

    return r.text, r.status_code, r.headers