Denis Bilenko avatar Denis Bilenko committed c038c2b

add common base class for websockets: WebSocket; if 'str' object is passed, assume it's utf-8, do not re-encode it

Comments (0)

Files changed (1)

geventwebsocket/websocket.py

     pass
 
 
-class WebSocketHixie(object):
+class WebSocket(object):
+
+    def _encode_text(self, s):
+        if isinstance(s, unicode):
+            return s.encode('utf-8')
+        elif isinstance(s, str):
+            return s
+        else:
+            raise TypeError("Expected 'unicode' or utf-8-encoded string: %r" % (s, ))
+
+
+class WebSocketHixie(WebSocket):
 
     def __init__(self, fobj, environ):
         self.origin = environ.get('HTTP_ORIGIN')
         self.fobj = fobj
         self._write = _get_write(fobj)
 
-    def _encode_text(self, s):
-        if isinstance(s, unicode):
-            return s.encode('utf-8')
-        elif isinstance(s, str):
-            return unicode(s).encode('utf-8')
-        else:
-            raise Exception('Invalid encoding')
-
     def send(self, message):
         message = self._encode_text(message)
 
                 raise WebSocketError("Received an invalid frame_type=%r" % frame_type)
 
 
-class WebSocketHybi(object):
+class WebSocketHybi(WebSocket):
     FIN = int("10000000", 2)
     RSV = int("01110000", 2)
     OPCODE = int("00001111", 2)
 
                 return msg
 
-    def _encode_text(self, s):
-        if isinstance(s, unicode):
-            return s.encode('utf-8')
-        elif isinstance(s, str):
-            return unicode(s).encode('utf-8')
-        else:
-            raise TypeError('Invalid encoding')
-
     def _is_valid_opcode(self, opcode):
         return opcode in (self.OPCODE_CONTINUATION, self.OPCODE_TEXT, self.OPCODE_BINARY,
             self.OPCODE_CLOSE, self.OPCODE_PING, self.OPCODE_PONG)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.