Browse files

fixed pylint and pep8 warnings

  • Loading branch information...
1 parent badfc23 commit da8edd91ee37bcf53aced325073c4c0bbc85408c @trey0 trey0 committed Sep 21, 2011
View
1 geocamPycroCom/CorbaWrapper.py
@@ -6,5 +6,6 @@
from PubSubWrapper import PubSubWrapper
+
class CorbaWrapper(PubSubWrapper):
pollForMessages = True
View
26 geocamPycroCom/Dispatcher.py
@@ -5,20 +5,22 @@
# __END_LICENSE__
import sys
+import comExceptions
+from comExceptions import BadEndpointError
import SharedScheduler
-from comExceptions import *
+
class Dispatcher:
- def __init__(self, moduleName, scheduler = None, period = 0.1):
+ def __init__(self, moduleName, scheduler=None, period=0.1):
if scheduler == None:
- import SharedScheduler
scheduler = SharedScheduler.scheduler
self._moduleName = moduleName
self._scheduler = scheduler
self._period = period
self._handlers = {}
self._protocols = {}
self._polling = False
+ self._handleMessagesTimer = None
def connectToNotificationService(self, notificationService):
protocol, addr = self._splitProtocol(notificationService)
@@ -45,7 +47,7 @@ def subscribe(self, event, handler):
def unsubscribe(self, event):
protocol, eventName = self._splitProtocol(event)
- protocol.unsubscribe(addr)
+ protocol.unsubscribe(eventName)
del self._handlers[eventName]
def publish(self, event, data):
@@ -76,7 +78,7 @@ def connect(self, endpoint, lineMode=True, readHandler=None, connectHandler=None
self._startHandling()
return sock
- def listen(self, endpoint, maxConnections=1, lineMode=True, acceptHandler=None,
+ def listen(self, endpoint, maxConnections=1, lineMode=True, acceptHandler=None,
connectHandler=None, readHandler=None, lineHandler=None, createSocketHandler=None):
protocol, addr = self._splitProtocol(endpoint)
sock = protocol.listen(self, addr,
@@ -85,12 +87,14 @@ def listen(self, endpoint, maxConnections=1, lineMode=True, acceptHandler=None,
acceptHandler=acceptHandler,
createSocketHandler=createSocketHandler,
connectHandler=connectHandler,
- readHandler=readHandler,
+ readHandler=readHandler,
lineHandler=lineHandler))
self._startHandling()
return sock
- def findServices(self, protoName, announceServices=[], serviceHandler=None):
+ def findServices(self, protoName, announceServices=None, serviceHandler=None):
+ if announceServices == None:
+ announceServices = []
if ':' in protoName:
protoName, _ = self._splitProtocol(protoName)
self.getProtocol(protoName).findServices(announceServices, serviceHandler)
@@ -109,15 +113,15 @@ def close(self):
def _loadProtocol(self, protoName, endpoint):
if protoName == 'console':
- protoName = 'file' # alias
- implName = '%sWrapper' % protoName.capitalize() # e.g. TcpWrapper
- modName = 'geocamPycroCom.%s' % implName # e.g. geocamPycroCom.tcpWrapper
+ protoName = 'file' # alias
+ implName = '%sWrapper' % protoName.capitalize() # e.g. TcpWrapper
+ modName = 'geocamPycroCom.%s' % implName # e.g. geocamPycroCom.tcpWrapper
try:
__import__(modName)
except ImportError:
raise BadEndpointError("can't load protocol", endpoint)
mod = sys.modules[modName]
- cls = getattr(mod, implName) # e.g. geocamPycroCom.TcpWrapper.TcpWrapper
+ cls = getattr(mod, implName) # e.g. geocamPycroCom.TcpWrapper.TcpWrapper
return cls(self, protoName)
def _splitProtocol(self, endpoint):
View
29 geocamPycroCom/FileStreamSocket.py
@@ -4,24 +4,35 @@
# All Rights Reserved.
# __END_LICENSE__
-import asyncore, sys, traceback, re
+import asyncore
+import sys
+import re
+
+# disable bogus warnings about attributes defined outside __init__
+# pylint: disable=W0201
OPTS_KEYS = ('lineMode', 'connectHandler', 'lineHandler')
+
class FileStreamSocket(asyncore.file_dispatcher):
- """Implement part of async_chat but on top of asyncore.file_dispatcher instead
+ """
+ Implement part of async_chat but on top of asyncore.file_dispatcher instead
of asyncore.dispatcher. Also implement default handlers for simple line-oriented
- I/O."""
+ I/O.
+ """
+
def __init__(self, optsDict):
+ # tell pylint we are ok with not calling the parent class constructor
+ # pylint: disable=W0231
for k in OPTS_KEYS:
setattr(self, '_' + k, optsDict[k])
- assert self._lineMode # wrapper only currently supports line buffering
+ assert self._lineMode # wrapper only currently supports line buffering
- def connect(self):
+ def connect(self): # pylint: disable=W0221
inputFd = sys.stdin.fileno()
self._outputFile = sys.stdout
asyncore.file_dispatcher.__init__(self, inputFd)
- self.set_terminator('\n') # default, can change
+ self.set_terminator('\n') # default, can change
self._ibuffer = []
def write(self, text):
@@ -52,7 +63,7 @@ def _processUpToTerminator(self, data):
else:
self.collect_incoming_data(data[:termIndex])
self.found_terminator()
- return data[(termIndex+1):]
+ return data[(termIndex + 1):]
def collect_incoming_data(self, data):
self._ibuffer.append(data)
@@ -62,9 +73,9 @@ def found_terminator(self):
line = re.sub(r'\r$', '', line)
self.handleLine(line)
self._ibuffer = []
-
+
def handle_error(self):
- raise # pass the buck to scheduler error handling
+ raise # pass the buck to scheduler error handling
def handleLine(self, line):
if self._lineHandler != None:
View
1 geocamPycroCom/FileWrapper.py
@@ -6,6 +6,7 @@
from FileStreamSocket import FileStreamSocket
+
class FileWrapper:
pollForMessages = False
View
1 geocamPycroCom/PubSubBaseSocket.py
@@ -4,6 +4,7 @@
# All Rights Reserved.
# __END_LICENSE__
+
class PubSubBaseSocket(object):
def __init__(self, protocol, dispatcher):
self._protocol = protocol
View
8 geocamPycroCom/PubSubListenSocket.py
@@ -8,20 +8,24 @@
from PubSubBaseSocket import PubSubBaseSocket
from PubSubStreamSocket import PubSubStreamSocket
+# disable bogus pylint warnings about trying to access or set missing class members
+# pylint: disable=E1101,W0201
+
OPTS_KEYS = ('maxConnections', 'acceptHandler', 'createSocketHandler')
+
class PubSubListenSocket(PubSubBaseSocket):
def __init__(self, protocol, dispatcher, optsDict):
super(PubSubListenSocket, self).__init__(protocol, dispatcher)
for k in OPTS_KEYS:
- setattr(self, '_'+k, optsDict[k])
+ setattr(self, '_' + k, optsDict[k])
self._optsDict = optsDict
def listen(self, listenEvent):
self.endpoint = '%s:%s' % (self._protocol.protoName, listenEvent)
self._listenEvent = listenEvent
self._protocol.subscribeWithHandler(self._listenEvent, self._pingHandler)
-
+
def _pingHandler(self, name, data):
cmd, self._acceptSendEvent = data.split()
assert cmd == 'ping'
View
16 geocamPycroCom/PubSubStreamSocket.py
@@ -4,16 +4,24 @@
# All Rights Reserved.
# __END_LICENSE__
-import re, platform, os, time
+# disable bogus pylint warnings about trying to access or set missing class members
+# pylint: disable=E1101,W0201
+
+import re
+import platform
+import os
+import time
+
from PubSubBaseSocket import PubSubBaseSocket
OPTS_KEYS = ('lineMode', 'connectHandler', 'readHandler', 'lineHandler')
+
class PubSubStreamSocket(PubSubBaseSocket):
def __init__(self, protocol, dispatcher, optsDict):
super(PubSubStreamSocket, self).__init__(protocol, dispatcher)
for k in OPTS_KEYS:
- setattr(self, '_'+k, optsDict[k])
+ setattr(self, '_' + k, optsDict[k])
self._clear()
def _getUniqueName(self):
@@ -57,7 +65,7 @@ def _checkForNewLine(self, data):
else:
line = ''.join(self._recvBuf) + data[:newLineIndex]
line = re.sub('\r$', '', line)
- self._recvBuf = [data[(newLineIndex+1):]]
+ self._recvBuf = [data[(newLineIndex + 1):]]
self.handleLine(line)
def read(self, numBytes=None):
@@ -72,7 +80,7 @@ def read(self, numBytes=None):
def write(self, data):
self._protocol.publish(self._sendEvent, data)
- push = write # emulate async_chat.push
+ push = write # emulate async_chat.push
def close(self):
self._clear()
View
9 geocamPycroCom/PubSubWrapper.py
@@ -4,24 +4,29 @@
# All Rights Reserved.
# __END_LICENSE__
+# disable bogus pylint warnings about trying to access or set missing class members
+# pylint: disable=E1101,W0201
+
from ServiceFinder import ServiceFinder
from PubSubStreamSocket import PubSubStreamSocket
from PubSubListenSocket import PubSubListenSocket
+
class PubSubWrapper(ServiceFinder):
def __init__(self, dispatcher, protoName):
+ super(PubSubWrapper, self).__init__()
self._dispatcher = dispatcher
self._protoName = protoName
self.setupProtocol()
-
+
def subscribeWithHandler(self, event, handler):
self._dispatcher.subscribe('%s:%s' % (self._protoName, event), handler)
def connect(self, dispatcher, pingEvent, optsDict):
sock = PubSubStreamSocket(self, dispatcher, optsDict)
sock.connect(pingEvent)
return sock
-
+
def listen(self, dispatcher, listenEvent, optsDict):
sock = PubSubListenSocket(self, dispatcher, optsDict)
sock.listen(listenEvent)
View
11 geocamPycroCom/ServiceFinder.py
@@ -4,11 +4,18 @@
# All Rights Reserved.
# __END_LICENSE__
+# disable bogus pylint warnings about trying to access or set missing class members
+# pylint: disable=E1101,W0201
+
import simplejson
+
class ServiceFinder(object):
"""Mixin that provides service finding functionality on top of a pub-sub protocol."""
+ def __init__(self):
+ pass
+
def findServices(self, announceServices, serviceHandler):
self._serviceHandler = serviceHandler
self._announceServices = {}
@@ -20,7 +27,7 @@ def findServices(self, announceServices, serviceHandler):
serviceName, serviceEvent = serviceEntry
self._announceServices[serviceName] = serviceEvent
self._startHandling()
-
+
def getAllServices(self):
return self._allServices
@@ -40,7 +47,7 @@ def _marcoHandler(self, event, data):
self.publish('polo', self._packMessageString())
def _poloHandler(self, event, data):
- moduleName, newServices = simplejson.loads(data)
+ _moduleName, newServices = simplejson.loads(data)
self._handleNewServices(newServices)
def _handleNewServices(self, newServices):
View
10 geocamPycroCom/SharedScheduler.py
@@ -4,12 +4,16 @@
# All Rights Reserved.
# __END_LICENSE__
-import sched, time, asyncore, sys
+import sched
+import time
+import asyncore
from printTraceback import printTraceback
+
class ExitSchedulerLoop(Exception):
pass
+
def asyncoreListenWait(delay):
if asyncore.socket_map:
asyncore.poll(delay)
@@ -18,6 +22,7 @@ def asyncoreListenWait(delay):
# avoid busy loop
time.sleep(delay)
+
class SchedulerPlus(sched.scheduler):
def __init__(self, timefunc, delayfunc):
def _delayPlus(delay):
@@ -53,11 +58,13 @@ def cancelSimple(self, event):
def enterPeriodic(self, period, action, argument=(), priority=1):
event = [None]
+
def _handler(*args):
#print 'enterPeriodic handler: args=%s' % str(args)
caughtException = self.runActionCatchExceptions(action, args)
if not caughtException:
event[0] = self.enterSimple(period, _handler, argument, priority)
+
event[0] = self.enterSimple(period, _handler, argument, priority)
return event
@@ -66,7 +73,6 @@ def cancelPeriodic(self, event):
def runForever(self):
try:
- self._exitNow = False
while 1:
self.run()
self.delayfunc(3600)
View
9 geocamPycroCom/TcpBaseSocket.py
@@ -4,13 +4,18 @@
# All Rights Reserved.
# __END_LICENSE__
+# suppress warnings about unimplemented abstract methods
+# pylint: disable=W0223
+
import asynchat
-import sys
+
class TcpBaseSocket(asynchat.async_chat):
def __init__(self, protocol, dispatcher):
+ asynchat.async_chat.__init__(self)
self._protocol = protocol
self._dispatcher = dispatcher
+ self._closed = False
def abort(self):
self.discard_buffers()
@@ -24,4 +29,4 @@ def handle_close(self):
def handle_error(self):
self.abort()
- raise # pass the buck to scheduler error handling
+ raise # pass the buck to scheduler error handling
View
113 geocamPycroCom/TcpListenSocket.py
@@ -4,56 +4,63 @@
# All Rights Reserved.
# __END_LICENSE__
-import sys, os, socket
-import asynchat
-from TcpBaseSocket import TcpBaseSocket
-from TcpStreamSocket import TcpStreamSocket
-from printTraceback import printTraceback
-
-OPTS_KEYS = ('maxConnections', 'acceptHandler', 'createSocketHandler')
-
-class TcpListenSocket(TcpBaseSocket):
- def __init__(self, protocol, dispatcher, optsDict):
- TcpBaseSocket.__init__(self, protocol, dispatcher)
- for k in OPTS_KEYS:
- setattr(self, '_'+k, optsDict[k])
- self._optsDict = optsDict
-
- def listen(self, listenPort):
- self.endpoint = '%s:%s' % (self._protocol._protoName, listenPort)
- self._host, self._portString = listenPort.split(':', 1)
- self._port = int(self._portString)
- if self._host == 'localhost':
- self._host = ''
- asynchat.async_chat.__init__(self)
- print '%s: starting' % self.__class__.__name__
- sys.stdout.flush()
- print ' creating socket'
- sys.stdout.flush()
- self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
- self.set_reuse_addr()
- print ' binding to port %d (on loopback interface only!)' % self._port
- sys.stdout.flush()
- self.bind((self._host, self._port))
- print ' port bound, calling listen'
- sys.stdout.flush()
- asynchat.async_chat.listen(self, self._maxConnections)
- print ' called listen'
- sys.stdout.flush()
-
- def handle_accept(self):
- if self._acceptHandler != None:
- self._acceptHandler(self)
- else:
- rawSock, addressInfo = self.accept()
- streamSock = self.handleCreateSocket()
- streamSock._initServerSocket(rawSock, addressInfo)
- self._protocol._sockets.add(streamSock)
- return streamSock
-
- def handleCreateSocket(self):
- """How to create a stream socket."""
- if self._createSocketHandler != None:
- return self._createSocketHandler(self)
- else:
- return TcpStreamSocket(self._protocol, self._dispatcher, self._optsDict)
+# suppress warnings about unimplemented abstract methods
+# pylint: disable=W0223
+
+import sys
+import socket
+import asynchat
+from TcpBaseSocket import TcpBaseSocket
+from TcpStreamSocket import TcpStreamSocket
+
+# disable bogus pylint warnings about trying to access or set missing class members
+# pylint: disable=E1101,W0201
+
+OPTS_KEYS = ('maxConnections', 'acceptHandler', 'createSocketHandler')
+
+
+class TcpListenSocket(TcpBaseSocket):
+ def __init__(self, protocol, dispatcher, optsDict):
+ TcpBaseSocket.__init__(self, protocol, dispatcher)
+ for k in OPTS_KEYS:
+ setattr(self, '_' + k, optsDict[k])
+ self._optsDict = optsDict
+
+ def listen(self, listenPort):
+ self.endpoint = '%s:%s' % (self._protocol._protoName, listenPort)
+ self._host, self._portString = listenPort.split(':', 1)
+ self._port = int(self._portString)
+ if self._host == 'localhost':
+ self._host = ''
+ asynchat.async_chat.__init__(self)
+ print '%s: starting' % self.__class__.__name__
+ sys.stdout.flush()
+ print ' creating socket'
+ sys.stdout.flush()
+ self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.set_reuse_addr()
+ print ' binding to port %d (on loopback interface only!)' % self._port
+ sys.stdout.flush()
+ self.bind((self._host, self._port))
+ print ' port bound, calling listen'
+ sys.stdout.flush()
+ asynchat.async_chat.listen(self, self._maxConnections)
+ print ' called listen'
+ sys.stdout.flush()
+
+ def handle_accept(self):
+ if self._acceptHandler != None:
+ self._acceptHandler(self)
+ else:
+ rawSock, addressInfo = self.accept()
+ streamSock = self.handleCreateSocket()
+ streamSock._initServerSocket(rawSock, addressInfo)
+ self._protocol._sockets.add(streamSock)
+ return streamSock
+
+ def handleCreateSocket(self):
+ """How to create a stream socket."""
+ if self._createSocketHandler != None:
+ return self._createSocketHandler(self)
+ else:
+ return TcpStreamSocket(self._protocol, self._dispatcher, self._optsDict)
View
165 geocamPycroCom/TcpStreamSocket.py
@@ -4,83 +4,88 @@
# All Rights Reserved.
# __END_LICENSE__
-import re, sys, os, socket, time, errno
-import exceptions, traceback
-import asynchat
-from TcpBaseSocket import TcpBaseSocket
-
-OPTS_KEYS = ('lineMode', 'connectHandler', 'lineHandler')
-
-class TcpStreamSocket(TcpBaseSocket):
- def __init__(self, protocol, dispatcher, optsDict):
- asynchat.async_chat.__init__(self)
- TcpBaseSocket.__init__(self, protocol, dispatcher)
- for k in OPTS_KEYS:
- setattr(self, '_' + k, optsDict[k])
- assert self._lineMode # wrapper currently only supports line buffering
- self._sock = None
-
- def connect(self, serverPort):
- self.endpoint = '%s:%s' % (self._protocol._protoName, serverPort)
- host, portString = serverPort.split(':', 1)
- port = int(portString)
- self.startup()
- self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
- #print 'connecting to server at %s' % self.endpoint
- asynchat.async_chat.connect(self, (host, port))
-
- def _initServerSocket(self, sock, addressInfo):
- self._sock = sock
- hostIp, hostPort = addressInfo
- try:
- hostName, _, _ = socket.gethostbyaddr(hostIp)
- except (socket.gaierror, socket.herror):
- # could not resolve hostname, just use ip address
- endpointHostName = hostIp
- else:
- endpointHostName = re.sub('\..*$', '', hostName)
- self.endpoint = '%s:%s:%s' % (self._protocol._protoName, endpointHostName, hostPort)
- print '\naccepting client connection from %s' % self.endpoint
- self.startup()
-
- def write(self, text):
- try:
- self.send(text)
- except socket.error:
- self.close()
- raise # let SharedScheduler handle the exception
-
- def startup(self):
- self._closed = False
- self._ibuffer = []
- if self._sock != None:
- self.set_socket(self._sock) # tell asyncore base class about the socket
- self.set_terminator('\n')
-
- def handle_connect(self):
- """What to do when we are connected."""
- if self._connectHandler:
- self._connectHandler(self)
-
- def handleLine(self, line):
- """What to do when we receive a line."""
- if self._lineHandler:
- self._lineHandler(self, line)
-
- def collect_incoming_data(self, data):
- self._ibuffer.append(data)
-
- def found_terminator(self):
- cmd = "".join(self._ibuffer)
- cmd = re.sub(r'\r$', '', cmd)
- self._ibuffer = []
- self.handleLine(cmd)
-
- def handle_error(self):
- errClass, errObject, errTB = sys.exc_info()[:3]
- if isinstance(errObject, socket.error) and errObject.args[0] == errno.ECONNREFUSED:
- print >>sys.stderr, 'connection to %s refused' % self.endpoint
- self.abort()
- else:
- self.abort()
- raise # pass the buck to SharedScheduler error handler
+# disable bogus pylint warnings about trying to access or set missing class members
+# pylint: disable=E1101,W0201
+
+import re
+import sys
+import socket
+import errno
+import asynchat
+from TcpBaseSocket import TcpBaseSocket
+
+OPTS_KEYS = ('lineMode', 'connectHandler', 'lineHandler')
+
+
+class TcpStreamSocket(TcpBaseSocket):
+ def __init__(self, protocol, dispatcher, optsDict):
+ TcpBaseSocket.__init__(self, protocol, dispatcher)
+ for k in OPTS_KEYS:
+ setattr(self, '_' + k, optsDict[k])
+ assert self._lineMode # wrapper currently only supports line buffering
+ self._sock = None
+
+ def connect(self, serverPort):
+ self.endpoint = '%s:%s' % (self._protocol._protoName, serverPort)
+ host, portString = serverPort.split(':', 1)
+ port = int(portString)
+ self.startup()
+ self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+ #print 'connecting to server at %s' % self.endpoint
+ asynchat.async_chat.connect(self, (host, port))
+
+ def _initServerSocket(self, sock, addressInfo):
+ self._sock = sock
+ hostIp, hostPort = addressInfo
+ try:
+ hostName, _, _ = socket.gethostbyaddr(hostIp)
+ except (socket.gaierror, socket.herror):
+ # could not resolve hostname, just use ip address
+ endpointHostName = hostIp
+ else:
+ endpointHostName = re.sub('\..*$', '', hostName)
+ self.endpoint = '%s:%s:%s' % (self._protocol._protoName, endpointHostName, hostPort)
+ print '\naccepting client connection from %s' % self.endpoint
+ self.startup()
+
+ def write(self, text):
+ try:
+ self.send(text)
+ except socket.error:
+ self.close()
+ raise # let SharedScheduler handle the exception
+
+ def startup(self):
+ self._closed = False
+ self._ibuffer = []
+ if self._sock != None:
+ self.set_socket(self._sock) # tell asyncore base class about the socket
+ self.set_terminator('\n')
+
+ def handle_connect(self):
+ """What to do when we are connected."""
+ if self._connectHandler:
+ self._connectHandler(self)
+
+ def handleLine(self, line):
+ """What to do when we receive a line."""
+ if self._lineHandler:
+ self._lineHandler(self, line)
+
+ def collect_incoming_data(self, data):
+ self._ibuffer.append(data)
+
+ def found_terminator(self):
+ cmd = "".join(self._ibuffer)
+ cmd = re.sub(r'\r$', '', cmd)
+ self._ibuffer = []
+ self.handleLine(cmd)
+
+ def handle_error(self):
+ _errClass, errObject, _errTB = sys.exc_info()[:3]
+ if isinstance(errObject, socket.error) and errObject.args[0] == errno.ECONNREFUSED:
+ print >> sys.stderr, 'connection to %s refused' % self.endpoint
+ self.abort()
+ else:
+ self.abort()
+ raise # pass the buck to SharedScheduler error handler
View
14 geocamPycroCom/TcpWrapper.py
@@ -4,10 +4,12 @@
# All Rights Reserved.
# __END_LICENSE__
+import sys
from TcpStreamSocket import TcpStreamSocket
from TcpListenSocket import TcpListenSocket
from WeakSet import WeakSet
+
class TcpWrapper:
pollForMessages = False
@@ -32,9 +34,9 @@ def close(self):
for sock in self._sockets:
try:
sock.close()
- except:
- errClass, errObject, errTB = sys.exc_info()[:3]
- print >>sys.stderr, ('could not close socket -- %s.%s: %s'
- % (errClass.__module__,
- errClass.__name__,
- str(errObject)))
+ except: # pylint: disable=W0702
+ errClass, errObject, _errTB = sys.exc_info()[:3]
+ print >> sys.stderr, ('could not close socket -- %s.%s: %s'
+ % (errClass.__module__,
+ errClass.__name__,
+ str(errObject)))
View
3 geocamPycroCom/WeakSet.py
@@ -6,6 +6,7 @@
from weakref import WeakKeyDictionary
+
class WeakSet(object):
def __init__(self):
self._vals = WeakKeyDictionary()
@@ -19,7 +20,7 @@ def remove(self, elt):
def __iter__(self):
# try to ensure that the dictionary doesn't change size during
# iteration by freezing it with the keys() function.
- self._tmp = self._vals.keys()
+ self._tmp = self._vals.keys() # pylint: disable=W0201
for elt in self._tmp:
yield elt
del self._tmp
View
141 geocamPycroCom/WebSockets.py
@@ -13,6 +13,10 @@
from geocamUtil.JsonRpc2Validation import JsonRpc2Validator
from geocamUtil.JsonRpc2Validation import JsonRpc2ComplianceException
+# disable bogus warnings about undefined class members
+# pylint: disable=E1101
+
+
class Resource(Thread):
def __init__(self, server, rname):
Thread.__init__(self)
@@ -21,7 +25,7 @@ def __init__(self, server, rname):
self.running = True
def receive(self, data):
- raise NotImplementedError( "Must be implemented in subclasses" )
+ raise NotImplementedError("Must be implemented in subclasses")
def send(self, data):
self.server.send(self.rname, data)
@@ -31,6 +35,9 @@ def stop(self):
class JsonRpc2Resource(Resource):
+ # tell pylint we are ok not implementing all abstract methods in this class
+ # pylint: disable=W0223
+
def __init__(self, server, rname):
Resource.__init__(self, server, rname)
self.validator = JsonRpc2Validator()
@@ -41,10 +48,12 @@ def genId(self):
def validate(self, data):
self.validator.validate(data)
- def sendRequest(self, method, paramObj={}):
- req = {JsonRpc2Keys.KEY_JSONRPC : '2.0',
- JsonRpc2Keys.KEY_METHOD : method,
- JsonRpc2Keys.KEY_ID : self.genId()
+ def sendRequest(self, method, paramObj=None):
+ if paramObj == None:
+ paramObj = {}
+ req = {JsonRpc2Keys.KEY_JSONRPC: '2.0',
+ JsonRpc2Keys.KEY_METHOD: method,
+ JsonRpc2Keys.KEY_ID: self.genId()
}
if paramObj:
req[JsonRpc2Keys.KEY_PARAMS] = paramObj
@@ -54,9 +63,11 @@ def sendRequest(self, method, paramObj={}):
self.validate(reqStr)
Resource.send(self, reqStr)
except ValueError as valerr:
- raise JsonRpc2ComplianceException( "Could not parse data into json object: %s"%str(valerr) )
+ raise JsonRpc2ComplianceException("Could not parse data into json object: %s" % str(valerr))
- def sendNotification(self, method, paramObj={}):
+ def sendNotification(self, method, paramObj=None):
+ if paramObj == None:
+ paramObj = {}
req = {JsonRpc2Keys.KEY_JSONRPC: '2.0',
JsonRpc2Keys.KEY_METHOD: method}
if paramObj:
@@ -66,34 +77,35 @@ def sendNotification(self, method, paramObj={}):
self.validate(reqStr)
Resource.send(self, reqStr)
except ValueError as valerr:
- raise JsonRpc2ComplianceException( "Could not parse data into json object: %s"%str(valerr) )
+ raise JsonRpc2ComplianceException("Could not parse data into json object: %s" % str(valerr))
- def sendSuccessResponse(self, id, result):
- resp = {JsonRpc2Keys.KEY_JSONRPC : '2.0',
- JsonRpc2Keys.KEY_ID : id,
- JsonRpc2Keys.KEY_RESULT : result}
+ def sendSuccessResponse(self, msgId, result):
+ resp = {JsonRpc2Keys.KEY_JSONRPC: '2.0',
+ JsonRpc2Keys.KEY_ID: msgId,
+ JsonRpc2Keys.KEY_RESULT: result}
try:
respStr = json.dumps(resp)
self.validate(respStr)
Resource.send(self, respStr)
except ValueError as valerr:
- raise JsonRpc2ComplianceException( "Could not parse data into json object: %s"%str(valerr) )
-
- def sendErrorResponse(self, id, errorCode, errorMsg):
- resp = {JsonRpc2Keys.KEY_JSONRPC : '2.0',
- JsonRpc2Keys.KEY_ID : id,
- JsonRpc2Keys.KEY_ERROR :
- {JsonRpc2Keys.KEY_ERROR_CODE : errorCode,
- JsonRpc2Keys.KEY_ERROR_MSG : errorMsg}}
+ raise JsonRpc2ComplianceException("Could not parse data into json object: %s" % str(valerr))
+
+ def sendErrorResponse(self, msgId, errorCode, errorMsg):
+ resp = {JsonRpc2Keys.KEY_JSONRPC: '2.0',
+ JsonRpc2Keys.KEY_ID: msgId,
+ JsonRpc2Keys.KEY_ERROR:
+ {JsonRpc2Keys.KEY_ERROR_CODE: errorCode,
+ JsonRpc2Keys.KEY_ERROR_MSG: errorMsg}}
try:
respStr = json.dumps(resp)
self.validate(respStr)
Resource.send(self, respStr)
except ValueError as valerr:
- raise JsonRpc2ComplianceException( "Could not parse data into json object: %s"%str(valerr) )
-
+ raise JsonRpc2ComplianceException("Could not parse data into json object: %s" % str(valerr))
+
def send(self, data):
- raise JsonRpc2ComplianceException( "Cannot send raw data to a JsonRpc2Resource" )
+ raise JsonRpc2ComplianceException("Cannot send raw data to a JsonRpc2Resource")
+
class ResourceManager(Thread):
def __init__(self, server):
@@ -102,35 +114,38 @@ def __init__(self, server):
self.resources = {}
self.running = {}
self.stopped = False
-
+
def registerResource(self, rname, resource):
self.resources[rname] = resource
def handleIncoming(self, rname, data):
- logging.info("ResourceManager: got msg for rname=[%s] msg=[%s]"%(rname, data))
+ logging.info("ResourceManager: got msg for rname=[%s] msg=[%s]", rname, data)
if rname in self.resources:
self.resources[rname].receive(data)
else:
- logging.info("[%s] not found in resource map."%rname)
+ logging.info("[%s] not found in resource map.", rname)
def run(self):
- for k,v in self.resources.items():
+ for k, v in self.resources.items():
v.start()
self.running[k] = v
while(not self.stopped):
time.sleep(5)
logging.debug("About to stop ResourceManager")
- for name, res in self.running.items():
+ for _name, res in self.running.items():
res.running = False
res.join()
self.running = {}
+
class DisconnectException(Exception):
- def __init__(self,msg):
+ def __init__(self, msg):
+ super(DisconnectException, self).__init__()
self.msg = msg
+
class WebSocket(object):
handshake = (
"HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
@@ -142,6 +157,7 @@ class WebSocket(object):
"Sec-Websocket-Location: ws://%(bind)s:%(port)s/%(resource)s\r\n"
"\r\n"
)
+
def __init__(self, client, server, resourceManager):
self.client = client
self.server = server
@@ -172,15 +188,15 @@ def feed(self, data):
raise DisconnectException('Looks like client shut down')
def dohandshake(self, header, key=None):
- logging.debug("Begin handshake: %s" % header)
+ logging.debug("Begin handshake: %s", header)
digitRe = re.compile(r'[^0-9]')
spacesRe = re.compile(r'\s')
part_1 = part_2 = origin = None
for line in header.split('\r\n'):
# Try splitting with spaces to see if we can find the GET first line
if self.associatedResourceName is None:
method, resource, proto = line.split(' ', 2)
- logging.debug("Method=[%s] Resource=[%s] Proto=[%s]"%(method,resource,proto))
+ logging.debug("Method=[%s] Resource=[%s] Proto=[%s]", method, resource, proto)
self.associatedResourceName = resource.strip('/')
continue
name, value = line.split(': ', 1)
@@ -202,7 +218,7 @@ def dohandshake(self, header, key=None):
part_2 = key_number_2 / spaces_2
elif name.lower() == "origin":
origin = value
- logging.debug("theResource=[%s]"%(self.associatedResourceName))
+ logging.debug("theResource=[%s]", self.associatedResourceName)
if part_1 and part_2:
logging.debug("Using challenge + response")
challenge = struct.pack('!I', part_1) + struct.pack('!I', part_2) + key
@@ -222,15 +238,15 @@ def dohandshake(self, header, key=None):
'bind': self.server.bind,
'resource': self.associatedResourceName
}
- logging.debug("Sending handshake %s" % handshake)
+ logging.debug("Sending handshake %s", handshake)
self.client.send(handshake)
return True
def onmessage(self, data):
- logging.info("Got message: [%s]. Passing to resource manager." % data)
+ logging.info("Got message: [%s]. Passing to resource manager.", data)
rname = self.associatedResourceName
- logging.info("About to pass client msg to resource manager with name=[%s]"%rname)
- self.resourceManager.handleIncoming(rname, data)
+ logging.info("About to pass client msg to resource manager with name=[%s]", rname)
+ self.resourceManager.handleIncoming(rname, data)
def send(self, data):
#logging.info("Sent message: %s" % data)
@@ -239,6 +255,7 @@ def send(self, data):
def close(self):
self.client.close()
+
class WebSocketServer(object):
def __init__(self, bind, port, cls):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -250,34 +267,37 @@ def __init__(self, bind, port, cls):
self.resourceManager = None
self.connections = {}
self.listeners = [self.socket]
+ self.running = False
# Map resource names to filenos
# This does not know anything about actual resource objects
# it just looks at incoming requests for specific resource names
# and associates connections to those names
- self.resourceMap = {}
+ self.resourceMap = {}
- def initResourceManager(self, cls, resourceList=[]):
+ def initResourceManager(self, cls, resourceList=None):
+ if resourceList == None:
+ resourceList = []
self.resourceManager = cls(self)
for r in resourceList:
self.resourceManager.registerResource(r.rname, r)
self.resourceManager.start()
-
+
def send(self, rname, data):
- logging.debug("WebSocketServer.send: got msg for rname=[%s] msg=[%s]"%(rname, data))
+ logging.debug("WebSocketServer.send: got msg for rname=[%s] msg=[%s]", rname, data)
if rname in self.resourceMap:
flist = self.resourceMap[rname]
for f in flist:
if f in self.connections:
self.connections[f].send(data)
else:
- logging.info("Could not find fileno [%d] in connection list"%f)
+ logging.info("Could not find fileno [%d] in connection list", f)
else:
- logging.info("Could not find [%s] in resource map."%rname)
-
+ logging.info("Could not find [%s] in resource map.", rname)
+
def sendToAll(self, msg):
# Send to all clients
- for id, conn in self.connections.items():
+ for _id, conn in self.connections.items():
conn.send(msg)
def halt(self):
@@ -286,20 +306,20 @@ def halt(self):
def listen(self, backlog=5):
self.socket.listen(backlog)
- logging.info("Listening on %s" % self.port)
+ logging.info("Listening on %s", self.port)
self.running = True
while self.running:
- rList, wList, xList = select(self.listeners, self.listeners, self.listeners, 1)
+ rList, _wList, xList = select(self.listeners, self.listeners, self.listeners, 1)
for ready in rList:
if ready == self.socket:
logging.debug("New client connection")
- client, address = self.socket.accept()
+ client, _address = self.socket.accept()
fileno = client.fileno()
- logging.debug("Added new client connection with id=[%d]"%fileno)
+ logging.debug("Added new client connection with id=[%d]", fileno)
self.listeners.append(fileno)
self.connections[fileno] = self.cls(client, self, self.resourceManager)
else:
- logging.debug("Client ready for reading %s" % ready)
+ logging.debug("Client ready for reading %s", ready)
client = self.connections[ready].client
data = client.recv(1024)
fileno = client.fileno()
@@ -317,8 +337,7 @@ def listen(self, backlog=5):
conn.close()
self.running = False
else:
- pass
- logging.debug("Closing client %s" % ready)
+ logging.debug("Closing client %s", ready)
self.connections[fileno].close()
del self.connections[fileno]
self.listeners.remove(ready)
@@ -329,16 +348,16 @@ def listen(self, backlog=5):
conn.close()
self.running = False
-class stdin_reader(asyncore.file_dispatcher):
- def __init__(self, file, server):
- asyncore.file_dispatcher.__init__(self, file)
- self.file = file
- self.server = server
+class stdin_reader(asyncore.file_dispatcher):
+ def __init__(self, fileobj, server):
+ asyncore.file_dispatcher.__init__(self, fileobj)
+ self.file = fileobj
+ self.server = server
- def handle_read(self):
- buf = self.file.read()
- self.server.sendToAll(buf)
+ def handle_read(self):
+ buf = self.file.read()
+ self.server.sendToAll(buf)
- def handle_write(self):
- pass
+ def handle_write(self):
+ pass
View
4 geocamPycroCom/comExceptions.py
@@ -4,14 +4,18 @@
# All Rights Reserved.
# __END_LICENSE__
+
class ComError(Exception):
pass
+
class DisconnectedError(ComError):
pass
+
class EventAlreadyBoundError(ComError):
pass
+
class BadEndpointError(ComError):
pass
View
27 geocamPycroCom/exampleClient.py
@@ -6,35 +6,40 @@
from Dispatcher import Dispatcher
from SharedScheduler import scheduler
-from exampleConfig import *
+import exampleConfig
+
def writeText(sock):
sock.write('hola\n')
+
def handleConnect(sock):
writeText(sock)
scheduler.enterPeriodic(period=2.0, action=lambda: writeText(sock))
+
def handleLine(sock, line):
print 'got:', line
+
def handleService(finder, serviceName, serviceEvent):
print 'handling notification of service %s at event %s' % (serviceName, serviceEvent)
- if serviceName == SERVER_ENDPOINT:
- sock = com.connect(serviceEvent,
- connectHandler = handleConnect,
- lineHandler = handleLine)
+ if serviceName == exampleConfig.SERVER_ENDPOINT:
+ com.connect(serviceEvent,
+ connectHandler=handleConnect,
+ lineHandler=handleLine)
+
def handleStdin(sock, line):
print 'you said:', line
com = Dispatcher(moduleName='exampleClient')
-if NOTIFY_ENDPOINT:
- com.connectToNotificationService(NOTIFY_ENDPOINT)
-if USE_SERVICE_DISCOVERY:
- com.findServices(protoName = PROTOCOL, serviceHandler = handleService)
+if exampleConfig.NOTIFY_ENDPOINT:
+ com.connectToNotificationService(exampleConfig.NOTIFY_ENDPOINT)
+if exampleConfig.USE_SERVICE_DISCOVERY:
+ com.findServices(protoName=exampleConfig.PROTOCOL, serviceHandler=handleService)
else:
- handleService(None, SERVER_ENDPOINT, SERVER_ENDPOINT)
-sock = com.connect('console:', lineHandler = handleStdin)
+ handleService(None, exampleConfig.SERVER_ENDPOINT, exampleConfig.SERVER_ENDPOINT)
+com.connect('console:', lineHandler=handleStdin)
com.runForever()
View
7 geocamPycroCom/exampleConfig.py
@@ -6,7 +6,6 @@
PROTOCOL = 'tcp'
-if PROTOCOL == 'tcp':
- SERVER_ENDPOINT = 'tcp:localhost:9085'
- NOTIFY_ENDPOINT = None
- USE_SERVICE_DISCOVERY = False
+SERVER_ENDPOINT = 'tcp:localhost:9085'
+NOTIFY_ENDPOINT = None
+USE_SERVICE_DISCOVERY = False
View
7 geocamPycroCom/examplePublisher.py
@@ -6,13 +6,14 @@
from Dispatcher import Dispatcher
from SharedScheduler import scheduler
-from exampleConfig import *
+import exampleConfig
+
def publishMessage():
- com.publish('%s:foo' % PROTOCOL, 'bar')
+ com.publish('%s:foo' % exampleConfig.PROTOCOL, 'bar')
print 'published message'
com = Dispatcher(moduleName='examplePublisher')
-com.connectToNotificationService(NOTIFY_ENDPOINT)
+com.connectToNotificationService(exampleConfig.NOTIFY_ENDPOINT)
scheduler.enterPeriodic(period=1.0, action=publishMessage)
scheduler.runForever()
View
18 geocamPycroCom/exampleServer.py
@@ -5,21 +5,23 @@
# __END_LICENSE__
from Dispatcher import Dispatcher
-from exampleConfig import *
+import exampleConfig
+
def handleConnect(sock):
print 'got connection'
+
def handleLine(sock, line):
print 'got:', line
sock.write('ciao\n')
com = Dispatcher(moduleName='exampleServer')
-if NOTIFY_ENDPOINT:
- com.connectToNotificationService(NOTIFY_ENDPOINT)
-com.listen(SERVER_ENDPOINT,
- connectHandler = handleConnect,
- lineHandler = handleLine)
-if USE_SERVICE_DISCOVERY:
- com.findServices(protoName = PROTOCOL, announceServices = [SERVER_ENDPOINT])
+if exampleConfig.NOTIFY_ENDPOINT:
+ com.connectToNotificationService(exampleConfig.NOTIFY_ENDPOINT)
+com.listen(exampleConfig.SERVER_ENDPOINT,
+ connectHandler=handleConnect,
+ lineHandler=handleLine)
+if exampleConfig.USE_SERVICE_DISCOVERY:
+ com.findServices(protoName=exampleConfig.PROTOCOL, announceServices=[exampleConfig.SERVER_ENDPOINT])
com.runForever()
View
8 geocamPycroCom/exampleSubscriber.py
@@ -4,15 +4,15 @@
# All Rights Reserved.
# __END_LICENSE__
-import time
from Dispatcher import Dispatcher
from SharedScheduler import scheduler
-from exampleConfig import *
+import exampleConfig
+
def fooHandler(name, data):
print 'got "%s" "%s"' % (name, data)
com = Dispatcher(moduleName='exampleSubscriber')
-com.connectToNotificationService(NOTIFY_ENDPOINT)
-com.subscribe('%s:foo' % PROTOCOL, fooHandler)
+com.connectToNotificationService(exampleConfig.NOTIFY_ENDPOINT)
+com.subscribe('%s:foo' % exampleConfig.PROTOCOL, fooHandler)
scheduler.runForever()
View
7 geocamPycroCom/printTraceback.py
@@ -9,14 +9,15 @@
import errno
import time
+
def printTraceback():
errClass, errObj, errTB = sys.exc_info()[:3]
while 1:
try:
traceback.print_tb(errTB)
- print >>sys.stderr, '%s.%s: %s' % (errClass.__module__,
- errClass.__name__,
- str(errObj))
+ print >> sys.stderr, '%s.%s: %s' % (errClass.__module__,
+ errClass.__name__,
+ str(errObj))
break
except IOError, exc:
if exc.args[0] == errno.EAGAIN:

0 comments on commit da8edd9

Please sign in to comment.