Skip to content

Commit b29b373

Browse files
author
Joel Collins
committed
Added flask-sockets module
1 parent e7ea853 commit b29b373

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed

labthings/server/sockets.py

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
"""
2+
Copyright (C) 2013 Kenneth Reitz
3+
4+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5+
6+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7+
8+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9+
"""
10+
11+
# -*- coding: utf-8 -*-
12+
13+
from werkzeug.routing import Map, Rule
14+
from werkzeug.exceptions import NotFound
15+
from werkzeug.http import parse_cookie
16+
from flask import request
17+
18+
19+
try:
20+
from geventwebsocket.gunicorn.workers import GeventWebSocketWorker as Worker
21+
from geventwebsocket.handler import WebSocketHandler
22+
from gunicorn.workers.ggevent import PyWSGIHandler
23+
24+
import gevent
25+
except ImportError:
26+
pass
27+
28+
29+
class SocketMiddleware(object):
30+
def __init__(self, wsgi_app, app, socket):
31+
self.ws = socket
32+
self.app = app
33+
self.wsgi_app = wsgi_app
34+
35+
def __call__(self, environ, start_response):
36+
adapter = self.ws.url_map.bind_to_environ(environ)
37+
try:
38+
handler, values = adapter.match()
39+
environment = environ["wsgi.websocket"]
40+
cookie = None
41+
if "HTTP_COOKIE" in environ:
42+
cookie = parse_cookie(environ["HTTP_COOKIE"])
43+
44+
with self.app.app_context():
45+
with self.app.request_context(environ):
46+
# add cookie to the request to have correct session handling
47+
request.cookie = cookie
48+
49+
handler(environment, **values)
50+
return []
51+
except (NotFound, KeyError):
52+
return self.wsgi_app(environ, start_response)
53+
54+
55+
class Sockets(object):
56+
def __init__(self, app=None):
57+
#: Compatibility with 'Flask' application.
58+
#: The :class:`~werkzeug.routing.Map` for this instance. You can use
59+
#: this to change the routing converters after the class was created
60+
#: but before any routes are connected.
61+
self.url_map = Map()
62+
63+
#: Compatibility with 'Flask' application.
64+
#: All the attached blueprints in a dictionary by name. Blueprints
65+
#: can be attached multiple times so this dictionary does not tell
66+
#: you how often they got attached.
67+
self.blueprints = {}
68+
self._blueprint_order = []
69+
70+
if app:
71+
self.init_app(app)
72+
73+
def init_app(self, app):
74+
app.wsgi_app = SocketMiddleware(app.wsgi_app, app, self)
75+
76+
def route(self, rule, **options):
77+
def decorator(f):
78+
endpoint = options.pop("endpoint", None)
79+
self.add_url_rule(rule, endpoint, f, **options)
80+
return f
81+
82+
return decorator
83+
84+
def add_url_rule(self, rule, _, f, **options):
85+
self.url_map.add(Rule(rule, endpoint=f))
86+
87+
def register_blueprint(self, blueprint, **options):
88+
"""
89+
Registers a blueprint for web sockets like for 'Flask' application.
90+
Decorator :meth:`~flask.app.setupmethod` is not applied, because it
91+
requires ``debug`` and ``_got_first_request`` attributes to be defined.
92+
"""
93+
first_registration = False
94+
95+
if blueprint.name in self.blueprints:
96+
assert self.blueprints[blueprint.name] is blueprint, (
97+
"A blueprint's name collision occurred between %r and "
98+
'%r. Both share the same name "%s". Blueprints that '
99+
"are created on the fly need unique names."
100+
% (blueprint, self.blueprints[blueprint.name], blueprint.name)
101+
)
102+
else:
103+
self.blueprints[blueprint.name] = blueprint
104+
self._blueprint_order.append(blueprint)
105+
first_registration = True
106+
107+
blueprint.register(self, options, first_registration)
108+
109+
110+
# CLI sugar.
111+
if "Worker" in locals() and "PyWSGIHandler" in locals() and "gevent" in locals():
112+
113+
class GunicornWebSocketHandler(PyWSGIHandler, WebSocketHandler):
114+
def log_request(self):
115+
if "101" not in self.status:
116+
super(GunicornWebSocketHandler, self).log_request()
117+
118+
Worker.wsgi_handler = GunicornWebSocketHandler
119+
worker = Worker

0 commit comments

Comments
 (0)