websocket: support Gunicorn environ['gunicorn.socket']

Now you able to upgrade connection with eventlet.websocket.WebSocketsWSGI when app runs under `gunicorn application:app -k eventlet`

https://github.com/eventlet/eventlet/pull/331
This commit is contained in:
catroot
2016-07-04 22:00:53 +03:00
committed by Sergey Shepelev
parent 863a1b7605
commit 6de8d478ca
2 changed files with 61 additions and 2 deletions

View File

@@ -135,7 +135,12 @@ class WebSocketWSGI(object):
return wsgi.ALREADY_HANDLED
def _handle_legacy_request(self, environ):
sock = environ['eventlet.input'].get_socket()
if 'eventlet.input' in environ:
sock = environ['eventlet.input'].get_socket()
elif 'gunicorn.socket' in environ:
sock = environ['gunicorn.socket']
else:
raise Exception('No eventlet.input or gunicorn.socket present in environ.')
if 'HTTP_SEC_WEBSOCKET_KEY1' in environ:
self.protocol_version = 76
@@ -192,7 +197,13 @@ class WebSocketWSGI(object):
return WebSocket(sock, environ, self.protocol_version)
def _handle_hybi_request(self, environ):
sock = environ['eventlet.input'].get_socket()
if 'eventlet.input' in environ:
sock = environ['eventlet.input'].get_socket()
elif 'gunicorn.socket' in environ:
sock = environ['gunicorn.socket']
else:
raise Exception('No eventlet.input or gunicorn.socket present in environ.')
hybi_version = environ['HTTP_SEC_WEBSOCKET_VERSION']
if hybi_version not in ('8', '13', ):
raise BadRequest(status='426 Upgrade Required',

View File

@@ -0,0 +1,48 @@
import eventlet.websocket
import gunicorn
import os
import random
import sys
@eventlet.websocket.WebSocketWSGI
def wsapp(ws):
ws.send(b'test pass')
ws.close()
def app(environ, start_response):
body = b'''<!doctype html>
<h1 id=status>loading...</h1>
<script>
(function(D) {
ws = new WebSocket('ws://127.0.0.1:5001/');
ws.onmessage = function(msg) {
var fr = new FileReader();
fr.onload = function(ev) {
D.getElementById('status').innerHTML = ev.target.result;
}
fr.readAsText(msg.data);
};
ws.onerror = function() {
D.getElementById('status').innerHTML = 'test fail';
}
})(document);
</script>
'''
if environ.get('HTTP_UPGRADE') == 'websocket':
return wsapp(environ, start_response)
start_response(
'200 OK', (
('Content-type', 'text/html'),
('Content-Length', str(len(body))),
('X-Gunicorn-Version', gunicorn.__version__),
),
)
return [body]
if __name__ == '__main__':
cmd = 'gunicorn websocket-gunicorn:app -b 127.0.0.1:5001 -k eventlet -w 1'
sys.stderr.write('exec ' + cmd + '\n')
os.system(cmd)