Skip to content

Instantly share code, notes, and snippets.

Last active May 14, 2019
What would you like to do?
Example of a gevent-based Flask server that aborts when downstream disconnects
Implements a behavior similar to:
- Go srv's cancelation of context on downstream disconnect
- PHP (unless `ignore_user_abort` is true)
import gevent.monkey
from contextlib import contextmanager
from flask import Flask
from gevent.wsgi import WSGIServer
app = Flask(__name__)
def _watchdog(reader, request_greenlet):
data = reader.peek()
if len(data) == 0:
print('detected socket shutdown')
def spawn_watchdog():
from flask import request
gr = gevent.spawn(_watchdog, request.environ['wsgi.input'].rfile, gevent.getcurrent())
yield gr
def index():
with spawn_watchdog():
print('start sleep')
print('end sleep')
return 'Hello World'
server = WSGIServer(('', 5000), app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment