rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
reactor.clientTCP('localhost', FTP_PORT, client)
factory = ClientFactory() factory.buildProtocol = lambda s,c=client: c reactor.connectTCP('localhost', FTP_PORT, factory)
def gotError(failure, x, errors_=errors): errors_[x] = failure
text += 'and ' + anchor
if len(authors) == 1: text = anchor else: text += 'and ' + anchor
def setAuthors(template, authors): # First, similarly to setTitle, insert text into an <div class="authors"> text = '' for name, href in authors: # FIXME: Do proper quoting/escaping (is it ok to use # xml.sax.saxutils.{escape,quoteattr}?) anchor = '<a href="%s">%s</a>' % (href, name) if (name, href) == authors[-1]: tex...
self.hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, environment, path, StartupInfo)
self.hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, env, path, StartupInfo)
def __init__(self, reactor, protocol, command, args, environment, path): self.reactor = reactor self.protocol = protocol
for n in "ttl", "received", "branch", "maddr", "rport":
for n in "ttl", "rport", "branch", "maddr", "received":
def toString(self): s = "SIP/2.0/%s %s:%s" % (self.transport, self.host, self.port) if self.hidden: s += ";hidden" for n in "ttl", "received", "branch", "maddr", "rport": value = getattr(self, n) if value == True: s += ";" + n elif value != None: s += ";%s=%s" % (n, value) return s
print "checking for NAT fixups"
def _fixupNAT(self, message, (srcHost, srcPort)): # RFC 2543 6.40.2, senderVia = parseViaHeader(message.headers["via"][0]) if senderVia.host != srcHost: senderVia.received = srcHost if senderVia.port != srcPort: senderVia.rport = srcPort message.headers["via"][0] = senderVia.toString() elif senderVia.rport == True: sen...
if not message.headers.has_key("authorization"):
import pprint; pprint.pprint(message.headers) if not message.headers.has_key("proxy-authorization"):
def handle_REGISTER_request(self, message, (host, port)): """Handle a registration request.
m.headers.setdefault('www-authenticate', []).append(value)
m.headers.setdefault('Proxy-Authenticate', []).append(value)
def unauthorized(self, message, host, port): m = self.responseFromRequest(407, message) for (scheme, auth) in self.authorizers.iteritems(): chal = auth.getChallenge((host, port)) if chal is None: value = '%s realm="%s"' % (scheme.title(), self.host) else: value = '%s %s,realm="%s"' % (scheme.title(), chal, self.host) m...
parts = message.headers['authorization'][0].split(None, 1)
parts = message.headers['proxy-authorization'][0].split(None, 1)
def login(self, message, host, port): parts = message.headers['authorization'][0].split(None, 1) a = self.authorizers.get(parts[0].lower()) if a: try: c = a.decode(parts[1]) except SIPError: raise except: log.err() self.deliverResponse(self.responseFromRequest(500, message)) else: c.username += '@' + self.host self.por...
process = getattr(self, 'processAnswer_%d' % message.answers[0].type, None)
process = getattr(self, 'processAnswer_%d' % self.type, None)
def getAnswer(self, message): self.done = 1 self.removeAll() if not message.answers: self.errback("No answers") return process = getattr(self, 'processAnswer_%d' % message.answers[0].type, None) if process is None: self.errback("No processor for answer type %s" % message.answers[0].type) return self.callback(process(me...
self.errback("No processor for answer type %s" % message.answers[0].type)
self.errback("No processor for answer type %s" % self.type)
def getAnswer(self, message): self.done = 1 self.removeAll() if not message.answers: self.errback("No answers") return process = getattr(self, 'processAnswer_%d' % message.answers[0].type, None) if process is None: self.errback("No processor for answer type %s" % message.answers[0].type) return self.callback(process(me...
self.callback(process(message))
process(message)
def getAnswer(self, message): self.done = 1 self.removeAll() if not message.answers: self.errback("No answers") return process = getattr(self, 'processAnswer_%d' % message.answers[0].type, None) if process is None: self.errback("No processor for answer type %s" % message.answers[0].type) return self.callback(process(me...
answer = random.choice(message.answers) return string.join(map(str, map(ord, answer.data)), '.')
answers, cnames, cnameMap = [], [], {} for answer in message.answers: if answer.type == 1: cnameMap[answer.name.name] = answer if answer.name.name != self.name: continue if answer.type == 1: answers.append(answer) elif answer.type == dns.CNAME: answer.strio.seek(answer.strioOff+2) n = dns.Name() n.decode(answer.strio) ...
def processAnswer_1(self, message): '''looking for name->address resolution choose one of the IPs at random''' answer = random.choice(message.answers) return string.join(map(str, map(ord, answer.data)), '.')
return ret
self.callback(ret)
def processAnswer_15(self, message): '''looking for Mail eXchanger for the domain
self.errback()
self.errback("Timed out")
def timeOut(self): if not self.done: self.removeAll() self.errback() self.done = 1
class ILookupTable:
class ILookupTable(Interface):
def nameprep(self, label): return label.lower()
def lookup(self, c):
def lookup(c):
def lookup(self, c): """ Return whether character is in this table. """
class IMappingTable:
class IMappingTable(Interface):
def lookup(self, c): """ Return whether character is in this table. """
def map(self, c):
def map(c):
def map(self, c): """ Return mapping for character. """
__implements__ = ILookupTable
implements(ILookupTable)
def map(self, c): """ Return mapping for character. """
__implements__ = ILookupTable
implements(ILookupTable)
def __init__(self, in_table_function): self.lookup = in_table_function
__implements__ = IMappingTable
implements(IMappingTable)
def lookup(self, c): return c in self._table
__implements__ = IMappingTable
implements(IMappingTable)
def __init__(self, map_table_function): self.map = map_table_function
self.deferred.callback(self.s.getvalue())
if self.deferred is not None: self.deferred.callback(self.s.getvalue())
def processEnded(self, reason): self.deferred.callback(self.s.getvalue())
heloFallback = 1
heloFallback = True
def sentMail(self, code, resp, numOk, addresses, log): """Called when an attempt to send an email is completed.
class SMTPSender(SMTPClient, SenderMixin):
class SMTPSender(SenderMixin, SMTPClient):
def sentMail(self, code, resp, numOk, addresses, log): self.factory.sendFinished = 1 if code not in SUCCESS: # Failure errlog = [] for addr, acode, aresp in addresses: if code not in SUCCESS: errlog.append("%s: %03d %s" % (addr, acode, aresp)) if numOk: errlog.append(str(log)) exc = SMTPDeliveryError(code, resp, '\n'.j...
class ESMTPSender(ESMTPClient, SenderMixin):
class ESMTPSender(SenderMixin, ESMTPClient):
def challengeResponse(self, secret, chal=1): if chal == 1: return "%s\0%s\0%s" % (self.user, self.user, secret) else: return "%s\0%s" % (self.user, secret)
def __init__(self, username, password, fromEmail, toEmail, file, deferred, retries=5):
def __init__(self, username, password, fromEmail, toEmail, file, deferred, retries=5, heloFallback=False, requireAuthentication=True, requireTransportSecurity=True):
def __init__(self, username, password, fromEmail, toEmail, file, deferred, retries=5): SMTPSenderFactory.__init__(self, fromEmail, toEmail, file, deferred, retries) self.username = username self.password = password
if hasattr(self.shell, 'logout') and self.shell.logout is not None: self.shell.logout()
def connectionLost(self, reason): log.msg("Oops! lost connection\n %s" % reason) # if we have a DTP protocol instance running and # we lose connection to the client's PI, kill the # DTP connection and close the port if self.dtpFactory: self.cleanupDTP() self.setTimeout(None) self.factory.currentInstanceNum -= 1
failure.trap(error.UnauthorizedLogin, error.UnhandledCredentials) self.reply(AUTH_FAILURE, '')
r = failure.trap(error.UnauthorizedLogin, TLDNotSetInRealmError) if r == TLDNotSetInRealmError: log.debug(failure.getErrorMessage()) self.reply(REQ_ACTN_NOT_TAKEN, 'internal server error') self.transport.loseConnection() else: self.reply(AUTH_FAILURE, '')
def _ebLogin(self, failure): # hack? error.UnhandledCredentials instead of...? failure.trap(error.UnauthorizedLogin, error.UnhandledCredentials) self.reply(AUTH_FAILURE, '')
def __init__(self, user=None):
uid = None gid = None clientwd = '/' filepath = None def __init__(self, user=None, tld=None):
def __init__(self, user=None): """Constructor @param user: the name of the user whose permissions we'll be using @type user: string """ self.user = user # user name self.uid = None # uid of anonymous user for shell self.gid = None # gid of anonymous user for shell self.clientwd = None...
self.uid = None self.gid = None self.clientwd = None self.tld = None
self.tld = tld
def __init__(self, user=None): """Constructor @param user: the name of the user whose permissions we'll be using @type user: string """ self.user = user # user name self.uid = None # uid of anonymous user for shell self.gid = None # gid of anonymous user for shell self.clientwd = None...
def _anonUserErrorMsg(self): pass
def _anonUserErrorMsg(self): pass
return "%s/%s" % (lpath, rpath)
return "%s%s%s" % (lpath, os.sep, rpath)
def myjoin(self, lpath, rpath): """does a dumb join between two path elements, ensuring there is only one '/' between them. pays no attention to the filesystem, unlike os.path.join @param lpath: path element to the left of the '/' in the result @type lpath: string @param rpath: path element to the right of the '/' in ...
avatar = FTPAnonymousShell() avatar.tld = self.tld
if self.tld is None: raise TLDNotSetInRealmError("you must set FTPRealm's tld to a non-None value before creating avatars!!!") avatar = FTPAnonymousShell(user=self.user, tld=self.tld)
def requestAvatar(self, avatarId, mind, *interfaces): if IFTPShell in interfaces: avatar = FTPAnonymousShell() avatar.tld = self.tld avatar.clientwd = self.clientwd avatar.user = self.user avatar.logout = self.logout return IFTPShell, avatar, avatar.logout raise NotImplementedError("Only IFTPShell interface is supporte...
avatar.user = self.user
def requestAvatar(self, avatarId, mind, *interfaces): if IFTPShell in interfaces: avatar = FTPAnonymousShell() avatar.tld = self.tld avatar.clientwd = self.clientwd avatar.user = self.user avatar.logout = self.logout return IFTPShell, avatar, avatar.logout raise NotImplementedError("Only IFTPShell interface is supporte...
def setUp(self):
def NOTsetUp(self):
def setUp(self): from twisted.internet import process process.Process.debug_child = True
def tearDown(self):
def NOTtearDown(self):
def tearDown(self): from twisted.internet import process process.Process.debug_child = False
task.schedule(self.connectionLost)
if self.connected: task.schedule(self.connectionLost)
def loseConnection(self): """ Stop accepting connections on this port.
print `data`
def dataReceived(self, data): print `data` self.peer.write(data)
self.transport.write(' '.join(self.args))
self.transport.write(' '.join(map(str, self.args)))
def connectionMade(self): self.transport.write(' '.join(self.args)) self.transport.loseConnection()
if not rpcConf.services.has_key(service.name):
protocol = protocol[4:] try: name, rpcVersions = service.name.split('rpc') except ValueError: log.msg('Bad RPC service/version: ' + service.name) continue if not rpcConf.services.has_key(name):
def main(options=None): # Parse options, read various config files if not options: options = InetdOptions() options.parseOptions() conf = inetdconf.InetdConf() conf.parseFile(open(options['file'])) rpcConf = inetdconf.RPCServicesConf() try: rpcConf.parseFile() except: # We'll survive even if we can't read /etc/rpc lo...
protocol = protocol[4:]
try: if '-' in rpcVersions: start, end = map(int, rpcVersions.split('-')) rpcVersions = range(start, end+1) else: rpcVersions = [int(rpcVersions)] except ValueError: log.msg('Bad RPC versions: ' + str(rpcVersions)) continue
def main(options=None): # Parse options, read various config files if not options: options = InetdOptions() options.parseOptions() conf = inetdconf.InetdConf() conf.parseFile(open(options['file'])) rpcConf = inetdconf.RPCServicesConf() try: rpcConf.parseFile() except: # We'll survive even if we can't read /etc/rpc lo...
if rpc: try: name, rpcVersions = service.name.split('rpc') except ValueError: log.msg('Bad RPC service/version: ' + service.name) continue try: if '-' in rpcVersions: start, end = map(int, rpcVersions.split('-')) rpcVersions = range(start, end+1) else: rpcVersions = [int(rpcVersions)] except ValueError: log.msg('Bad R...
def main(options=None): # Parse options, read various config files if not options: options = InetdOptions() options.parseOptions() conf = inetdconf.InetdConf() conf.parseFile(open(options['file'])) rpcConf = inetdconf.RPCServicesConf() try: rpcConf.parseFile() except: # We'll survive even if we can't read /etc/rpc lo...
o2.callRemote("getCache").addCallback(coll.append) o2.callRemote("getCache").addCallback(coll.append)
o2.callRemote("getCache").addCallback(coll.append).addErrback(coll.append) o2.callRemote("getCache").addCallback(coll.append).addErrback(coll.append)
def testCache(self): c, s, pump = connectedServerAndClient() obj = NestedCache() obj2 = NestedComplicatedCache() vcc = obj2.c s.setNameForLocal("obj", obj) s.setNameForLocal("xxx", obj2) o2 = c.remoteForName("obj") o3 = c.remoteForName("xxx") coll = [] o2.callRemote("getCache").addCallback(coll.append) o2.callRemote("g...
if sys.hexversion >= 0x2000000:
if sys.hexversion >= 0x2000000 and os.name != "java":
def testCache(self): c, s, pump = connectedServerAndClient() obj = NestedCache() obj2 = NestedComplicatedCache() vcc = obj2.c s.setNameForLocal("obj", obj) s.setNameForLocal("xxx", obj2) o2 = c.remoteForName("obj") o3 = c.remoteForName("xxx") coll = [] o2.callRemote("getCache").addCallback(coll.append) o2.callRemote("g...
self.transport.loseConnection() from twisted.internet import reactor
self.terminal.loseConnection()
def handle_QUIT(self): self.transport.loseConnection() from twisted.internet import reactor reactor.stop()
try: del self.channelsToRemoteChannel[channel] except KeyError: pass
del self.channelsToRemoteChannel[channel]
def ssh_CHANNEL_CLOSE(self, packet): localChannel = struct.unpack('>L', packet[: 4])[0] channel = self.channels[localChannel] channel.closed() del self.localToRemoteChannel[localChannel] del self.channels[localChannel] try: del self.channelsToRemoteChannel[channel] except KeyError: pass # we'd already closed this end
del self.channelsToRemoteChannel[channel]
def sendClose(self, channel): """ Close a channel.
tlvData = reduce(lambda x,y: x+y, map(lambda (k,v):TLV(k,v), self.tlvs.items())) or '\000\000'
tlvData = reduce(lambda x,y: x+y, map(lambda (k,v):TLV(k,v), self.tlvs.items()), '\000\000')
def oscarRep(self, groupID, buddyID): tlvData = reduce(lambda x,y: x+y, map(lambda (k,v):TLV(k,v), self.tlvs.items())) or '\000\000' return struct.pack('!H', len(self.name)) + self.name + \ struct.pack('!HH', groupID, buddyID) + '\000\000' + tlvData
reflect.accumulateClassList(self.__class__, 'flags', flags)
def _gather_flags(self): """Gather up boolean (flag) options. """
reflect.accumulateClassList(self.__class__, 'parameters', parameters)
def _gather_parameters(self): """Gather options which take a value. """ longOpt, shortOpt = [], '' docs, settings, synonyms, dispatch = {}, {}, {}, {}
class ClientContextFactory(ContextFactory): """A sample context factory for SSL clients."""
class ClientContextFactory: """A context factory for SSL clients.""" isClient = 1
def getContext(self): """Create an SSL context. """ return self._context
return CONNECTION_LOST
return main.CONNECTION_LOST
def _postLoseConnection(self): """Gets called after loseConnection(), after buffered data is sent.
return CONNECTION_DONE
return main.CONNECTION_DONE
def _postLoseConnection(self): """Gets called after loseConnection(), after buffered data is sent.
"AdapterRegistry"]
"AdapterRegistry", "Adapter"]
def upgradeToVersion1(self): # To let Componentized instances interact correctly with # rebuild(), we cannot use class objects as dictionary keys. for (k, v) in self._adapterCache.items(): self._adapterCache[reflect.qual(k)] = v
"""a method that will be called if and when an error occurs in the user-defined-method It will be called callable(fail, *a, **kw), where fail is a L{twisted.python.failure.Failure} object.
"""a method that will be called if and when an error occurs in the user-defined-method. It will be called callable(fail, *a, **kw), where fail is a L{twisted.python.failure.Failure} object.
def addErrback(callable, *a, **kw): """a method that will be called if and when an error occurs in the user-defined-method It will be called callable(fail, *a, **kw), where fail is a L{twisted.python.failure.Failure} object. @return: self """
logErrCheck = zi.Attribute("""@cvar doLogErrCheck: perform check and cleanup of log.errs @type doLogErrCheck: Boolean""") cleanPending = zi.Attribute("""@cvar cleanPending: check and cleanup of left-over reactor.delayedCalls @type cleanPending: Boolean""") cleanThreads = zi.Attribute("""@cvar cleanThreads: perform cl...
logErrCheck = zi.Attribute( """@cvar doLogErrCheck: perform check and cleanup of log.errs @type doLogErrCheck: Boolean""") cleanPending = zi.Attribute( """@cvar cleanPending: check and cleanup of left-over reactor.DelayedCalls @type cleanPending: Boolean""") cleanThreads = zi.Attribute( """@cvar cleanThreads: perform...
def addErrback(callable, *a, **kw): """a method that will be called if and when an error occurs in the user-defined-method It will be called callable(fail, *a, **kw), where fail is a L{twisted.python.failure.Failure} object. @return: self """
duration = zi.Attribute("a float representing how long, in seconds, the framework should wait before timing out") excClass = zi.Attribute("the exception to raise if the timeout duration is exceeded") excArg = zi.Attribute("the argument to excClass that the timeout will raise")
duration = zi.Attribute("a float representing how long, in seconds, the " "framework should wait before timing out") excClass = zi.Attribute("the exception to raise if the timeout duration " "is exceeded") excArg = zi.Attribute( "the argument to excClass that the timeout will raise")
def __add__(other): """returns .msg + other, for string concatenation"""
todo = zi.Attribute("""@ivar todo: indicates whether or not this method has been marked todo, @type todo: this is the value of the .todo attribute or returns None""") skip = zi.Attribute("""@ivar skip: indicates whether or not this method has been skipped, same semantics as .todo @type skip: string @note: a TestMethod...
todo = zi.Attribute( """@ivar todo: indicates whether or not this method has been marked as 'todo' @type todo: this is the value of the .todo attribute, or None""") skip = zi.Attribute( """@ivar skip: indicates whether or not this method has been skipped, same semantics as .todo @type skip: string @note: a TestMethod ...
def runTests(): """runs this test class"""
def registerReapProccessHandler(pid, process):
def registerReapProcessHandler(pid, process):
def registerReapProccessHandler(pid, process): if reapProcessHandlers.has_key(pid): raise RuntimeError try: aux_pid, status = os.waitpid(pid, os.WNOHANG) except: log.deferr() aux_pid = None if aux_pid: process.processEnded(status) else: reapProcessHandlers[pid] = process
def unregisterReapProccessHandler(pid, process):
def unregisterReapProcessHandler(pid, process):
def unregisterReapProccessHandler(pid, process): if not (reapProcessHandlers.has_key(pid) and reapProcessHandlers[pid] == process): raise RuntimeError del reapProcessHandlers[pid]
registerReapProccessHandler(self.pid, self)
registerReapProcessHandler(self.pid, self)
def __init__(self, reactor, command, args, environment, path, proto, uid=None, gid=None): """Spawn an operating-system process.
registerReapProccessHandler(self.pid, self)
registerReapProcessHandler(self.pid, self)
def __init__(self, reactor, command, args, environment, path, proto, uid=None, gid=None, usePTY=None): """Spawn an operating-system process.
"""Add the given message to the currently selected mailbox
"""Add the given message to the given mailbox.
def append(self, mailbox, message, flags = (), date = None): """Add the given message to the currently selected mailbox
'-v '
def testOurServerCmdLineClient(self): """test the Conch server against the cmdline client """ if runtime.platformType == 'win32': raise unittest.SkipTest, "can't run cmdline client on win32" cmd = ('%s %s -p %i -l testuser ' '--known-hosts kh_test ' '--user-authentications publickey ' '--host-key-algorithms ssh-rsa ' '...
'-v '
def testOurServerUnixClient(self): if runtime.platformType == 'win32': raise unittest.SkipTest, "can't run cmdline client on win32" cmd1 = ('-p %i -l testuser ' '--known-hosts kh_test ' '--user-authentications publickey ' '--host-key-algorithms ssh-rsa ' '-a ' '-K direct ' '-i dsa_test ' 'localhost' ) cmd2 = ('%s %s -p...
self.connected = 1
def doConnect(self): """I connect the socket.
self.startReading()
def _connectDone(self): self.startReading() self.protocol = self.connector.buildProtocol(self.getPeer()) self.protocol.makeConnection(self) self.logstr = self.protocol.__class__.__name__+",client"
self.startReading()
def _connectDone(self): self.startReading() self.protocol = self.connector.buildProtocol(self.getPeer()) self.protocol.makeConnection(self) self.logstr = self.protocol.__class__.__name__+",client"
if self.attributeDesc!=None:
if attributeDesc!=None:
def __init__(self, attributeDesc=None, assertionValue=None, encoded=None, berdecoder=None): BERSequence.__init__(self, value=[]) if self.attributeDesc!=None: assert encoded==None self.attributeDesc=attributeDesc self.assertionValue=assertionValue elif encoded!=None: assert attributeDesc==None assert assertionValue==Non...
self.service.connectionLost(self.name)
self.service.connectionLost(self.name, self.transport.pid)
def processEnded(self, reason): if not self.empty: self.output.dataReceived('\n') self.service.connectionLost(self.name)
def connectionLost(self, name): if self.murder.has_key(name): self.murder[name].cancel() del self.murder[name] return del self.protocols[name]
def connectionLost(self, name, pid): if self.murder.has_key(pid): self.murder[pid].cancel() del self.murder[pid] if self.protocols.has_key(name): del self.protocols[name]
def connectionLost(self, name): if self.murder.has_key(name): self.murder[name].cancel() del self.murder[name] return del self.protocols[name] if time.time()-self.timeStarted[name]<self.threshold: delay = self.delay[name] = min(1+2*self.delay.get(name, 0), 3600) else: delay = self.delay[name] = 0 if self.active and sel...
self.murder[name] = reactor.callLater(self.killTime, os.kill, pid, 9)
self.murder[pid] = reactor.callLater(self.killTime, os.kill, pid, 9)
def stopProcess(self, name): if not self.protocols.has_key(name): return pid = self.protocols[name].transport.pid del self.protocols[name] os.kill(pid, 15) self.murder[name] = reactor.callLater(self.killTime, os.kill, pid, 9)
self.startProcess(name)
def restartAll(self): for name in self.processes.keys(): self.stopProcess(name) self.startProcess(name)
def printAnswer(answers):
def printAnswer((answers, auth, add)):
def printAnswer(answers): if not len(answers): print 'No answers' else: print '\n'.join(map(str, answers)) reactor.stop()
print '\n'.join(map(str, answers))
print '\n'.join([str(x.payload) for x in answers])
def printAnswer(answers): if not len(answers): print 'No answers' else: print '\n'.join(map(str, answers)) reactor.stop()
dirListingPage = widgets.WidgetPage(DirectoryListing(self.path)) return dirListingPage.render(request)
return self.redirect(request).render(request)
def render(self, request): "You know what you doing." mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime =\ os.stat(self.path)
def locate(self, name, debug=1):
def locate(self, name, debug=0):
def locate(self, name, debug=1): """ Get a reference to an object with the given name which is somewhere on the path above us. """ return self._lookup(name, debug=debug)
def acquire(self, name, debug=1):
def acquire(self, name, debug=0):
def acquire(self, name, debug=1): """ Look for an attribute or element by name in all of our parents """ return self._lookup(name, acquire=1, debug=debug)
class YieldIteration(Exception):
class PauseFlow(Exception):
def iter(lst): from types import ListType, TupleType if type(lst) == type([]) or type(lst) == type(tuple()): return _ListIterator(lst) else: return lst.__iter__()
This exception can be used as a signal from an iterator returned from an IFlowFunction; the Flow object could then reschedule itself in the event queue so that other operations can proceed. In this case, the iterator's next() will just be called at a later time. ''' initialState = "__initial__" failureState = "__fa...
This exception can be used as a signal from a stage in the flow to the flow controller. It can occur in either the __call__ of the stage, or in the next() method of any iterator returned. The result of this signal is that the entire flow mechanism is paused and recheduled in the main loop so that other operations in...
def iter(lst): from types import ListType, TupleType if type(lst) == type([]) or type(lst) == type(tuple()): return _ListIterator(lst) else: return lst.__iter__()
This is an interface for a function (with attributes) which participates in a given Flow. It is typical to implement this using a function given attributes. Every attribute may be missing to provide minimal behavior. isIterable This is true if the function returns an iterable object; in 2.1 this is either a list o...
This function constructs a FlowStage tuple which is used inside the Flow mechanism to track state, etc. If an argument is provided, then it is used; otherwise the callable is searched for the same attribute, else, the default is used. onFinish This function attribute, if present, will be called after all subordin...
def iter(lst): from types import ListType, TupleType if type(lst) == type([]) or type(lst) == type(tuple()): return _ListIterator(lst) else: return lst.__iter__()
Note: if none of these attributes are provided, then the function is expected to return a tuple with two items, a (state, value) or None to stop the flow. ''' def __call__(self, data): ''' When the function is invoked, it is passed a single argument, the data for the call. To stop further interaction within the Flow, ...
onFailure This is a callable attribute, that, if present will be executed when ever an error occurs processing any of the children. This callable is applied with the an stack of IFlowFunction, and the current data value. The onFinish function can remedy the problem by returning a valid value, or can cancel recursi...
def iter(lst): from types import ListType, TupleType if type(lst) == type([]) or type(lst) == type(tuple()): return _ListIterator(lst) else: return lst.__iter__()
This is a state machine driven data consumer. Flow objects are used to run data from a producer, such as a database query, through various filter functions until the data is eventually consumed and None is returned. As data is introduced into the Flow using the 'run' method, the Flow looks up the appropriate handler,...
This is a state machine driven data consumer. Flow stages are used to run data from a producer, such as a database query, through various filter functions until the data is eventually consumed and None is returned. As data is introduced into the Flow using the 'run' method, the Flow looks up the appropriate handler, ...
def onFailure(self, state, data, failure): ''' This function attribute, if present, will be called when ever an error occurs in processing any of the children, This callable is applied with the state, and data of the failing call. Either None, or a (state, value) tuple should be returned from this function; if a tuple...
def __init__(self, *bases): ''' Initializes a Flow object, optionally using one or more subordinate flow objects for default behavior. The stack is used when the currently executing object wants to be notified that all children have finished processing. ''' self.states = {} self.bases = bases or [] self.s...
def __init__(self): ''' Initializes a Flow object. Processing starts at initialStage and then proceeds recursively. Note that the stages are implemented as a singly-linked list, where each link is an array containing a FlowStage, and the next link. ''' self.stageHead = None self.stageTail = None self.callStack ...
def __init__(self, *bases): ''' Initializes a Flow object, optionally using one or more subordinate flow objects for default behavior. The stack is used when the currently executing object wants to be notified that all children have finished processing. ''' self.states = {} self.bases = bases or [] self.s...
def register(self, func, state = initialState, nextState = None, isIterable = 0, onFinish = None, onFailure = None, stopValue = None): ''' This allows the registration of callback functions which are applied whenever an appropriate event of a given state is encountered. Each callback item, run, start, and finish can e...
def addStage(self, callable, onFinish = None, isIterable = None, isDynamic = None, stopValue = None, onFailure = None): ''' This appends an additional stage to the singly-linked list, starting with stageHead. ''' stage = FlowStage(callable, onFinish, isIterable, isDynamic, stopValue, onFailure) link = FlowStageLink(sta...
def register(self, func, state = initialState, nextState = None, isIterable = 0, onFinish = None, onFailure = None, stopValue = None): ''' This allows the registration of callback functions which are applied whenever an appropriate event of a given state is encountered. Each callback item, run, start, and finish can e...
trace("running flow") stack = self.stack if not(stack): stack.append((state, data, None, None, None))
assert not linktail, "not implemented" stack = self.callStack if not stack: self.callStack = stack = [] link = self.stageHead stack.append((_STACK_STAGE, (link, data)))
def run(self, data = None, state=initialState): ''' This executes the current flow, given empty starting data and the default initial state. ''' trace("running flow") stack = self.stack if not(stack): stack.append((state, data, None, None, None)) while stack: (state, data, finish, itr, stop) = stack[-1] if finish: fini...
(state, data, finish, itr, stop) = stack[-1] if finish: finish()
(kind, param) = stack[-1] if _STACK_FINISH == kind: param()
def run(self, data = None, state=initialState): ''' This executes the current flow, given empty starting data and the default initial state. ''' trace("running flow") stack = self.stack if not(stack): stack.append((state, data, None, None, None)) while stack: (state, data, finish, itr, stop) = stack[-1] if finish: fini...
elif itr: trace("-> iterator")
if _STACK_DYNAMIC == kind: (flow, data, linknext) = param ret = flow.run(data, linknext) if ret: return ret stack.pop() continue if _STACK_ITERATOR == kind: (iterator, stop, linknext) = param
def run(self, data = None, state=initialState): ''' This executes the current flow, given empty starting data and the default initial state. ''' trace("running flow") stack = self.stack if not(stack): stack.append((state, data, None, None, None)) while stack: (state, data, finish, itr, stop) = stack[-1] if finish: fini...
data = itr.next() if data is stop: continue if not state: (state, data) = data if data is stop: continue
data = iterator.next() if data is stop: continue param = (linknext, data)
def run(self, data = None, state=initialState): ''' This executes the current flow, given empty starting data and the default initial state. ''' trace("running flow") stack = self.stack if not(stack): stack.append((state, data, None, None, None)) while stack: (state, data, finish, itr, stop) = stack[-1] if finish: fini...
trace("-> stop")
def run(self, data = None, state=initialState): ''' This executes the current flow, given empty starting data and the default initial state. ''' trace("running flow") stack = self.stack if not(stack): stack.append((state, data, None, None, None)) while stack: (state, data, finish, itr, stop) = stack[-1] if finish: fini...
except YieldIteration: trace("-> yield")
except PauseFlow:
def run(self, data = None, state=initialState): ''' This executes the current flow, given empty starting data and the default initial state. ''' trace("running flow") stack = self.stack if not(stack): stack.append((state, data, None, None, None)) while stack: (state, data, finish, itr, stop) = stack[-1] if finish: fini...
return else: stack.pop() tpl = self._lookup(state) (func, state, isIterable, finish, failure, stop) = tpl if finish: stack.append((state, None, finish, None, stop))
return 1 (link, data) = param (func, finish, isIterable, isDynamic, stop, failure) = link.stage if _STACK_STAGE == kind: stack.pop() if finish: stack.append((_STACK_FINISH,finish))
def run(self, data = None, state=initialState): ''' This executes the current flow, given empty starting data and the default initial state. ''' trace("running flow") stack = self.stack if not(stack): stack.append((state, data, None, None, None)) while stack: (state, data, finish, itr, stop) = stack[-1] if finish: fini...
trace("-> item")
if data is stop: continue if isDynamic: (data, flow) = data stack.append((_STACK_DYNAMIC,(flow, data, link.next ))) continue
def run(self, data = None, state=initialState): ''' This executes the current flow, given empty starting data and the default initial state. ''' trace("running flow") stack = self.stack if not(stack): stack.append((state, data, None, None, None)) while stack: (state, data, finish, itr, stop) = stack[-1] if finish: fini...
if data: data = iter(data) self.stack.append((state, None, None,data, stop)) else: if data is stop: continue if not state: (state, data) = data if data is stop: continue stack.append((state, data, None, None, stop)) trace("end flow") def __str__(self,indlvl=0): indent = "\n" + " " * indlvl indent2 = indent + " ...
iterator = iter(data) param = (iterator, stop, link.next) stack.append((_STACK_ITERATOR,param)) continue stack.append((_STACK_STAGE,(link.next,data))) def __call__(self, data): self.run(data) def testFlow(): ''' Test basic Flow operation ''' def dataSource(data): return [1, 1+data, 1+data*2] def addOne(data): return...
def run(self, data = None, state=initialState): ''' This executes the current flow, given empty starting data and the default initial state. ''' trace("running flow") stack = self.stack if not(stack): stack.append((state, data, None, None, None)) while stack: (state, data, finish, itr, stop) = stack[-1] if finish: fini...
regular iterators, this one throws a YieldIteration exception
regular iterators, this one throws a PauseFlow exception
def __str__(self,indlvl=0): indent = "\n" + " " * indlvl indent2 = indent + " " return "%sFlow: %s%s%s%s%s" % ( indent,repr(self),indent2, indent2.join(self.states.keys()),indent, "".join(map(lambda a: a.__str__(indlvl+1), self.bases)))
raise YieldIteration
raise PauseFlow
def next(self): if self.buff: return self.buff.pop(0) if self.isFinished: raise StopIteration if self.failure: raise self.failure raise YieldIteration
f.register(CountIterator(),nextState='print',onFinish=printDone) f.register(printResult,'print')
f.addStage(CountIterator(),onFinish=printDone) f.addStage(printResult)
def printResult(x): print x
pool = ConnectionPool("mx.ODBC.EasySoft","PSICustomerProto")
pool = ConnectionPool("mx.ODBC.EasySoft","<somedsn>")
def testFlowConnect(): from twisted.enterprise.adbapi import ConnectionPool pool = ConnectionPool("mx.ODBC.EasySoft","PSICustomerProto") def printResult(x): print x def printDone(): print "done" f = Flow() sql = "SELECT caption from vw_date" f.register(FlowQueryIterator(pool,sql),nextState='print') f.register(printResu...
sql = "SELECT caption from vw_date" f.register(FlowQueryIterator(pool,sql),nextState='print') f.register(printResult,'print')
f.waitInterval = 1 f.addStage(FlowQueryIterator(pool,sql),onFinish=printDone) f.addStage(printResult)
def printDone(): print "done"