Debian Codegraph @

geventwebsocket/resource.py

raw symbols SCIP
1 import re
2 import warnings
3
4 from .protocols.base import BaseProtocol
5 from .exceptions import WebSocketError
6
7 try:
8 from collections import OrderedDict
9 except ImportError:
10 class OrderedDict:
11 pass
12
13
14 class WebSocketApplication(object):
15 protocol_class = BaseProtocol
16
17 def __init__(self, ws):
18 self.protocol = self.protocol_class(self)
19 self.ws = ws
20
21 def handle(self):
22 self.protocol.on_open()
23
24 while True:
25 try:
26 message = self.ws.receive()
27 except WebSocketError:
28 self.protocol.on_close()
29 break
30
31 self.protocol.on_message(message)
32
33 def on_open(self, *args, **kwargs):
34 pass
35
36 def on_close(self, *args, **kwargs):
37 pass
38
39 def on_message(self, message, *args, **kwargs):
40 self.ws.send(message, **kwargs)
41
42 @classmethod
43 def protocol_name(cls):
44 return cls.protocol_class.PROTOCOL_NAME
45
46
47 class Resource(object):
48 def __init__(self, apps=None):
49 self.apps = apps if apps else []
50
51 if isinstance(apps, dict):
52 if not isinstance(apps, OrderedDict):
53 warnings.warn("Using an unordered dictionary for the "
54 "app list is discouraged and may lead to "
55 "undefined behavior.", UserWarning)
56
57 self.apps = apps.items()
58
59 # An app can either be a standard WSGI application (an object we call with
60 # __call__(self, environ, start_response)) or a class we instantiate
61 # (and which can handle websockets). This function tells them apart.
62 # Override this if you have apps that can handle websockets but don't
63 # fulfill these criteria.
64 def _is_websocket_app(self, app):
65 return isinstance(app, type) and issubclass(app, WebSocketApplication)
66
67 def _app_by_path(self, environ_path, is_websocket_request):
68 # Which app matched the current path?
69 for path, app in self.apps:
70 if re.match(path, environ_path):
71 if is_websocket_request == self._is_websocket_app(app):
72 return app
73 return None
74
75 def app_protocol(self, path):
76 # app_protocol will only be called for websocket apps
77 app = self._app_by_path(path, True)
78
79 if hasattr(app, 'protocol_name'):
80 return app.protocol_name()
81 else:
82 return ''
83
84 def __call__(self, environ, start_response):
85 environ = environ
86 is_websocket_call = 'wsgi.websocket' in environ
87 current_app = self._app_by_path(environ['PATH_INFO'], is_websocket_call)
88
89 if current_app is None:
90 raise Exception("No apps defined")
91
92 if is_websocket_call:
93 ws = environ['wsgi.websocket']
94 current_app = current_app(ws)
95 current_app.ws = ws # TODO: needed?
96 current_app.handle()
97 # Always return something, calling WSGI middleware may rely on it
98 return []
99 else:
100 return current_app(environ, start_response)