Skip to content

Instantly share code, notes, and snippets.

@ikonst
Last active May 14, 2019
Embed
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
gevent.monkey.patch_all()
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')
request_greenlet.kill()
@contextmanager
def spawn_watchdog():
from flask import request
gr = gevent.spawn(_watchdog, request.environ['wsgi.input'].rfile, gevent.getcurrent())
yield gr
gr.kill()
@app.route('/')
def index():
with spawn_watchdog():
print('start sleep')
gevent.sleep(2)
print('end sleep')
return 'Hello World'
server = WSGIServer(('127.0.0.1', 5000), app)
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment