1 | 1 |
|
2 | 2 |
from werkzeug.routing import Map, Rule
|
3 | 3 |
from werkzeug.exceptions import NotFound
|
4 | |
|
5 | |
|
6 | |
def log_request(self):
|
7 | |
log = self.server.log
|
8 | |
if log:
|
9 | |
if hasattr(log, 'info'):
|
10 | |
log.info(self.format_request() + '\n')
|
11 | |
else:
|
12 | |
log.write(self.format_request() + '\n')
|
|
4 |
from werkzeug.http import parse_cookie
|
|
5 |
from flask import request
|
13 | 6 |
|
14 | 7 |
|
15 | 8 |
# Monkeys are made for freedom.
|
16 | 9 |
try:
|
|
10 |
from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker
|
|
11 |
from geventwebsocket.handler import WebSocketHandler
|
|
12 |
from gunicorn.workers.ggevent import PyWSGIHandler
|
|
13 |
|
17 | 14 |
import gevent
|
18 | |
from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker
|
19 | 15 |
except ImportError:
|
20 | 16 |
pass
|
21 | |
|
22 | |
|
23 | |
if 'gevent' in locals():
|
24 | |
# Freedom-Patch logger for Gunicorn.
|
25 | |
if hasattr(gevent, 'pywsgi'):
|
26 | |
gevent.pywsgi.WSGIHandler.log_request = log_request
|
27 | 17 |
|
28 | 18 |
|
29 | 19 |
class SocketMiddleware(object):
|
|
38 | 28 |
try:
|
39 | 29 |
handler, values = adapter.match()
|
40 | 30 |
environment = environ['wsgi.websocket']
|
|
31 |
cookie = None
|
|
32 |
if 'HTTP_COOKIE' in environ:
|
|
33 |
cookie = parse_cookie(environ['HTTP_COOKIE'])
|
41 | 34 |
|
42 | 35 |
with self.app.app_context():
|
43 | 36 |
with self.app.request_context(environ):
|
|
37 |
# add cookie to the request to have correct session handling
|
|
38 |
request.cookie = cookie
|
|
39 |
|
44 | 40 |
handler(environment, **values)
|
45 | 41 |
return []
|
46 | 42 |
except (NotFound, KeyError):
|
|
104 | 100 |
|
105 | 101 |
|
106 | 102 |
# CLI sugar.
|
107 | |
if 'Worker' in locals():
|
|
103 |
if ('Worker' in locals() and 'PyWSGIHandler' in locals() and
|
|
104 |
'gevent' in locals()):
|
|
105 |
|
|
106 |
class GunicornWebSocketHandler(PyWSGIHandler, WebSocketHandler):
|
|
107 |
def log_request(self):
|
|
108 |
if '101' not in self.status:
|
|
109 |
super(GunicornWebSocketHandler, self).log_request()
|
|
110 |
|
|
111 |
Worker.wsgi_handler = GunicornWebSocketHandler
|
108 | 112 |
worker = Worker
|