Flask send stream as response
<p>I'm trying to "proxy" my Flask server (i will call it Server#01) with another server(Server#02). It's working well except for one thing : when the Server#01 use send_from_directory(), i don't know how to re-send this file. </p>

<p><strong>My classic "proxy"</strong></p>

<pre><code>result = requests.get(my_path_to_server01)
return Response(stream_with_context(result.iter_content()), 
                content_type = result.headers['Content-Type'])
</code></pre>

<p>With a file a response, it's taking hours... So i tried many things. The one who work is :</p>

<pre><code>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')
</code></pre>

<p>I would like to "redirect" my response ("result" variable), or send/copy a stream of my file. Anyways I don't want to use a physical file because it don't seems the proper way in my mind and i can imagine all problems who can happens because of that.</p>

<p>There should not be any problem with your "classic" proxy other than that it should use <code>stream=True</code>, and specify a <code>chunk_size</code> for <code>response.iter_content()</code>.</p>

<p>By default <code>chunk_size</code> is 1 byte, so the streaming will be very inefficient and consequently very slow. Trying a larger chunk size, e.g. 10K should yield faster transfers. Here's some code for the proxy.</p>

<pre><code>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)
</code></pre>

<p>You don't even need to use <code>stream_with_context()</code> here because you don't need access to the request context within the generator returned by <code>iter_content()</code>.</p>

python redirect flask proxy