Make a non-blocking request with requests when running Flask with Gunicorn and Gevent
<p>My Flask application will receive a request, do some processing, and then make a request to a slow external endpoint that takes 5 seconds to respond.  It looks like running Gunicorn with Gevent will allow it to handle many of these slow requests at the same time.  How can I modify the example below so that the view is non-blocking?</p>

<pre><code>import requests

@app.route('/do', methods = ['POST'])
def do():
    result = requests.get('slow api')
    return result.content
</code></pre>

<pre class="lang-none prettyprint-override"><code>gunicorn server:app -k gevent -w 4
</code></pre>

<p>You can use <code>grequests</code>. It allows other greenlets to run while the request is made. It is compatible with the <code>requests</code> library and returns a <code>requests.Response</code> object. The usage is as follows:</p>

<pre><code>import grequests

@app.route('/do', methods = ['POST'])
def do():
    result = grequests.map([grequests.get('slow api')])
    return result[0].content
</code></pre>

<p>Edit: I've added a test and saw that the time didn't improve with grequests since gunicorn's gevent worker already performs monkey-patching when it is initialized: <a href="https://github.com/benoitc/gunicorn/blob/master/gunicorn/workers/ggevent.py#L65" rel="nofollow">https://github.com/benoitc/gunicorn/blob/master/gunicorn/workers/ggevent.py#L65</a></p>

python flask python-requests gunicorn gevent