Linking callback to default greenlet setup for socket io

19 views
Skip to first unread message

ams.fwd

unread,
Jul 17, 2015, 5:46:42 PM7/17/15
to gev...@googlegroups.com
Hi All.

I am trying to hook a post request callback to a flask streaming response where my app is running under gevent. What I would like to do is to run a callback after the *entire* response has been streamed. Sample (broken) code attached.

What I would like is to somehow link the post_response callback to greenlet that is spawned for the request. Is there any way to do that?

TIA
AM
repro.py

Jason Madden

unread,
Jul 17, 2015, 6:17:24 PM7/17/15
to gev...@googlegroups.com

> On Jul 17, 2015, at 16:46, ams.fwd <ams...@gmail.com> wrote:
>
> What I would like is to somehow link the post_response callback to greenlet that is spawned for the request. Is there any way to do that?

You can link a callback to the current greenlet running the request and it will be called when the greenlet finishes (and the socket is closed). But gevent knows nothing about flask responses and doesn't buffer any part of the data that your application sends, so if you need more context you'll have to make it available somehow yourself.

from gevent import getcurrent
from gevent import pywsgi

def application(env, start_response):
def callback(greenlet):
print("I am called when greenlet finishes")
getcurrent().link(callback)

start_response('200 OK', [])
return [b'Hello World']

if __name__ == '__main__':
server = pywsgi.WSGIServer(('0.0.0.0', 5000), application)
server.serve_forever()

ams.fwd

unread,
Jul 17, 2015, 6:44:56 PM7/17/15
to gev...@googlegroups.com
Ah! getcurrent was what I was looking for.

Thanks.
AM
Reply all
Reply to author
Forward
0 new messages