我花了很多时间做同样的事情,最终找到了一个使用requests库的解决方案,它似乎运行良好。它甚至可以在一个响应中设置多个 cookie,这需要进行一些调查才能弄清楚。这是烧瓶视图函数:

  1. from flask import request, Response
  2. import requests
  3. def _proxy(*args, **kwargs):
  4. resp = requests.request(
  5. method=request.method,
  6. url=request.url.replace(request.host_url, 'new-domain.com'),
  7. headers={key: value for (key, value) in request.headers if key != 'Host'},
  8. data=request.get_data(),
  9. cookies=request.cookies,
  10. allow_redirects=False)
  11. excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
  12. headers = [(name, value) for (name, value) in resp.raw.headers.items()
  13. if name.lower() not in excluded_headers]
  14. response = Response(resp.content, resp.status_code, headers)
  15. return response

根据Proxying to another web service with FlaskDownload large file in python with requestsFlask large file download我设法在流模式下制作了一个 Flask HTTP 代理。

  1. from flask import Flask, request, Response
  2. import requests
  3. PROXY_URL = 'http://ipv4.download.thinkbroadband.com/'
  4. def download_file(streamable):
  5. with streamable as stream:
  6. stream.raise_for_status()
  7. for chunk in stream.iter_content(chunk_size=8192):
  8. yield chunk
  9. def _proxy(*args, **kwargs):
  10. resp = requests.request(
  11. method=request.method,
  12. url=request.url.replace(request.host_url, PROXY_URL),
  13. headers={key: value for (key, value) in request.headers if key != 'Host'},
  14. data=request.get_data(),
  15. cookies=request.cookies,
  16. allow_redirects=False,
  17. stream=True)
  18. excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
  19. headers = [(name, value) for (name, value) in resp.raw.headers.items()
  20. if name.lower() not in excluded_headers]
  21. return Response(download_file(resp), resp.status_code, headers)
  22. app = Flask(__name__)
  23. @app.route('/', defaults={'path': ''})
  24. @app.route('/<path:path>')
  25. def download(path):
  26. return _proxy()
  27. if __name__ == '__main__':
  28. app.run(host='0.0.0.0', port=1234, debug=True)

参考

https://stackoverflow.com/questions/6656363/proxying-to-another-web-service-with-flask
https://stackoverflow.com/questions/62552660/how-to-forward-http-range-requests-using-python-and-flask?noredirect=1&lq=1
https://stackoverflow.com/questions/6656363/proxying-to-another-web-service-with-flask
https://stackoverflow.com/questions/16694907/download-large-file-in-python-with-requests