forked from heroku-python/flask-sockets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflask_sockets.py
74 lines (57 loc) · 1.99 KB
/
flask_sockets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# -*- coding: utf-8 -*-
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import NotFound
def log_request(self):
log = self.server.log
if log:
if hasattr(log, 'info'):
log.info(self.format_request() + '\n')
else:
log.write(self.format_request() + '\n')
# Monkeys are made for freedom.
try:
import gevent
from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker
except ImportError:
pass
if 'gevent' in locals():
# Freedom-Patch logger for Gunicorn.
if hasattr(gevent, 'pywsgi'):
gevent.pywsgi.WSGIHandler.log_request = log_request
class SocketMiddleware(object):
def __init__(self, wsgi_app, app, socket):
self.ws = socket
self.app = app
self.wsgi_app = wsgi_app
def __call__(self, environ, start_response):
adapter = self.ws.url_map.bind_to_environ(environ)
try:
handler, values = adapter.match()
environment = environ.get('wsgi.websocket')
if environment:
with self.app.app_context():
with self.app.request_context(environ):
handler(environment, **values)
return []
else:
return self.wsgi_app(environ, start_response)
except NotFound:
return self.wsgi_app(environ, start_response)
class Sockets(object):
def __init__(self, app=None):
self.url_map = Map()
if app:
self.init_app(app)
def init_app(self, app):
app.wsgi_app = SocketMiddleware(app.wsgi_app, app, self)
def route(self, rule, **options):
def decorator(f):
endpoint = options.pop('endpoint', None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
def add_url_rule(self, rule, _, f, **options):
self.url_map.add(Rule(rule, endpoint=f))
# CLI sugar.
if 'Worker' in locals():
worker = Worker