Ben*_*n K 5 python proxy redirect flask
我正试图用另一台服务器(Server#02)"代理"我的Flask服务器(我称之为Server#01).它运行良好除了一件事:当服务器#01使用send_from_directory()时,我不知道如何重新发送此文件.
我的经典"代理人"
result = requests.get(my_path_to_server01)
return Response(stream_with_context(result.iter_content()),
content_type = result.headers['Content-Type'])
Run Code Online (Sandbox Code Playgroud)
随着文件的响应,它需要几个小时...所以我尝试了很多东西.工作的人是:
result = requests.get(my_path_to_server01, stream=True)
with open('img.png', 'wb') as out_file:
shutil.copyfileobj(result.raw, out_file)
return send_from_directory('./', 'img.png')
Run Code Online (Sandbox Code Playgroud)
我想"重定向"我的响应("结果"变量),或发送/复制我的文件流.无论如何我不想使用物理文件,因为它似乎不是我心中的正确方式,我可以想象所有可能因此发生的问题.
除了应该使用的"经典"代理之外,应该没有任何问题stream=True,并指定chunk_sizefor response.iter_content().
默认情况下chunk_size是1个字节,因此流式传输效率非常低,因此非常慢.尝试更大的块大小,例如10K,可以产生更快的传输速度.这是代理的一些代码.
import requests
from flask import Flask, Response, stream_with_context
app = Flask(__name__)
my_path_to_server01 = 'http://localhost:5000/'
@app.route("/")
def streamed_proxy():
r = requests.get(my_path_to_server01, stream=True)
return Response(r.iter_content(chunk_size=10*1024),
content_type=r.headers['Content-Type'])
if __name__ == "__main__":
app.run(port=1234)
Run Code Online (Sandbox Code Playgroud)
您甚至不需要在stream_with_context()此处使用,因为您不需要访问返回的生成器中的请求上下文iter_content().
| 归档时间: |
|
| 查看次数: |
7530 次 |
| 最近记录: |