我花了很多时间做同样的事情,最终找到了一个使用requests库的解决方案,它似乎运行良好。它甚至可以在一个响应中设置多个 cookie,这需要进行一些调查才能弄清楚。这是烧瓶视图函数:
from flask import request, Response
import requests
def _proxy(*args, **kwargs):
resp = requests.request(
method=request.method,
url=request.url.replace(request.host_url, 'new-domain.com'),
headers={key: value for (key, value) in request.headers if key != 'Host'},
data=request.get_data(),
cookies=request.cookies,
allow_redirects=False)
excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
headers = [(name, value) for (name, value) in resp.raw.headers.items()
if name.lower() not in excluded_headers]
response = Response(resp.content, resp.status_code, headers)
return response
根据Proxying to another web service with Flask,Download large file in python with requests和Flask large file download我设法在流模式下制作了一个 Flask HTTP 代理。
from flask import Flask, request, Response
import requests
PROXY_URL = 'http://ipv4.download.thinkbroadband.com/'
def download_file(streamable):
with streamable as stream:
stream.raise_for_status()
for chunk in stream.iter_content(chunk_size=8192):
yield chunk
def _proxy(*args, **kwargs):
resp = requests.request(
method=request.method,
url=request.url.replace(request.host_url, PROXY_URL),
headers={key: value for (key, value) in request.headers if key != 'Host'},
data=request.get_data(),
cookies=request.cookies,
allow_redirects=False,
stream=True)
excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
headers = [(name, value) for (name, value) in resp.raw.headers.items()
if name.lower() not in excluded_headers]
return Response(download_file(resp), resp.status_code, headers)
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def download(path):
return _proxy()
if __name__ == '__main__':
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