code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def popCommandQueue(self): """ Return the front element of the command queue, or None if empty. """ if self.actionQueue: return self.actionQueue.pop(0) else: return None
Return the front element of the command queue, or None if empty.
popCommandQueue
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def queueLogin(self, username, password): """ Login: send the username, send the password. If the password is L{None}, the PASS command won't be sent. Also, if the response to the USER command has a response code of 230 (User logged in), then PASS won't be sent either. """ # Prepare the USER command deferreds = [] userDeferred = self.queueStringCommand('USER ' + username, public=0) deferreds.append(userDeferred) # Prepare the PASS command (if a password is given) if password is not None: passwordCmd = FTPCommand('PASS ' + password, public=0) self.queueCommand(passwordCmd) deferreds.append(passwordCmd.deferred) # Avoid sending PASS if the response to USER is 230. # (ref: http://cr.yp.to/ftp/user.html#user) def cancelPasswordIfNotNeeded(response): if response[0].startswith('230'): # No password needed! self.actionQueue.remove(passwordCmd) return response userDeferred.addCallback(cancelPasswordIfNotNeeded) # Error handling. for deferred in deferreds: # If something goes wrong, call fail deferred.addErrback(self.fail) # But also swallow the error, so we don't cause spurious errors deferred.addErrback(lambda x: None)
Login: send the username, send the password. If the password is L{None}, the PASS command won't be sent. Also, if the response to the USER command has a response code of 230 (User logged in), then PASS won't be sent either.
queueLogin
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def lineReceived(self, line): """ (Private) Parses the response messages from the FTP server. """ # Add this line to the current response if bytes != str: line = line.decode(self._encoding) if self.debug: log.msg('--> %s' % line) self.response.append(line) # Bail out if this isn't the last line of a response # The last line of response starts with 3 digits followed by a space codeIsValid = re.match(r'\d{3} ', line) if not codeIsValid: return code = line[0:3] # Ignore marks if code[0] == '1': return # Check that we were expecting a response if self.nextDeferred is None: self.fail(UnexpectedResponse(self.response)) return # Reset the response response = self.response self.response = [] # Look for a success or error code, and call the appropriate callback if code[0] in ('2', '3'): # Success self.nextDeferred.callback(response) elif code[0] in ('4', '5'): # Failure self.nextDeferred.errback(failure.Failure(CommandFailed(response))) else: # This shouldn't happen unless something screwed up. log.msg('Server sent invalid response code %s' % (code,)) self.nextDeferred.errback(failure.Failure(BadResponse(response))) # Run the next command self.sendNextCommand()
(Private) Parses the response messages from the FTP server.
lineReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def __init__(self, username='anonymous', password='[email protected]', passive=1): """ Constructor. I will login as soon as I receive the welcome message from the server. @param username: FTP username @param password: FTP password @param passive: flag that controls if I use active or passive data connections. You can also change this after construction by assigning to C{self.passive}. """ FTPClientBasic.__init__(self) self.queueLogin(username, password) self.passive = passive
Constructor. I will login as soon as I receive the welcome message from the server. @param username: FTP username @param password: FTP password @param passive: flag that controls if I use active or passive data connections. You can also change this after construction by assigning to C{self.passive}.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def fail(self, error): """ Disconnect, and also give an error to any queued deferreds. """ self.transport.loseConnection() self._fail(error)
Disconnect, and also give an error to any queued deferreds.
fail
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def receiveFromConnection(self, commands, protocol): """ Retrieves a file or listing generated by the given command, feeding it to the given protocol. @param commands: list of strings of FTP commands to execute then receive the results of (e.g. C{LIST}, C{RETR}) @param protocol: A L{Protocol} B{instance} e.g. an L{FTPFileListProtocol}, or something that can be adapted to one. Typically this will be an L{IConsumer} implementation. @return: L{Deferred}. """ protocol = interfaces.IProtocol(protocol) wrapper = ProtocolWrapper(protocol, defer.Deferred()) return self._openDataConnection(commands, wrapper)
Retrieves a file or listing generated by the given command, feeding it to the given protocol. @param commands: list of strings of FTP commands to execute then receive the results of (e.g. C{LIST}, C{RETR}) @param protocol: A L{Protocol} B{instance} e.g. an L{FTPFileListProtocol}, or something that can be adapted to one. Typically this will be an L{IConsumer} implementation. @return: L{Deferred}.
receiveFromConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def queueLogin(self, username, password): """ Login: send the username, send the password, and set retrieval mode to binary """ FTPClientBasic.queueLogin(self, username, password) d = self.queueStringCommand('TYPE I', public=0) # If something goes wrong, call fail d.addErrback(self.fail) # But also swallow the error, so we don't cause spurious errors d.addErrback(lambda x: None)
Login: send the username, send the password, and set retrieval mode to binary
queueLogin
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def sendToConnection(self, commands): """ XXX @return: A tuple of two L{Deferred}s: - L{Deferred} L{IFinishableConsumer}. You must call the C{finish} method on the IFinishableConsumer when the file is completely transferred. - L{Deferred} list of control-connection responses. """ s = SenderProtocol() r = self._openDataConnection(commands, s) return (s.connectedDeferred, r)
XXX @return: A tuple of two L{Deferred}s: - L{Deferred} L{IFinishableConsumer}. You must call the C{finish} method on the IFinishableConsumer when the file is completely transferred. - L{Deferred} list of control-connection responses.
sendToConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def doPassive(response): """Connect to the port specified in the response to PASV""" host, port = decodeHostPort(response[-1][4:]) f = _PassiveConnectionFactory(protocol) _mutable[0] = self.connectFactory(host, port, f)
Connect to the port specified in the response to PASV
_openDataConnection.doPassive
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _openDataConnection(self, commands, protocol): """ This method returns a DeferredList. """ cmds = [FTPCommand(command, public=1) for command in commands] cmdsDeferred = defer.DeferredList([cmd.deferred for cmd in cmds], fireOnOneErrback=True, consumeErrors=True) cmdsDeferred.addErrback(_unwrapFirstError) if self.passive: # Hack: use a mutable object to sneak a variable out of the # scope of doPassive _mutable = [None] def doPassive(response): """Connect to the port specified in the response to PASV""" host, port = decodeHostPort(response[-1][4:]) f = _PassiveConnectionFactory(protocol) _mutable[0] = self.connectFactory(host, port, f) pasvCmd = FTPCommand('PASV') self.queueCommand(pasvCmd) pasvCmd.deferred.addCallback(doPassive).addErrback(self.fail) results = [cmdsDeferred, pasvCmd.deferred, protocol.deferred] d = defer.DeferredList(results, fireOnOneErrback=True, consumeErrors=True) d.addErrback(_unwrapFirstError) # Ensure the connection is always closed def close(x, m=_mutable): m[0] and m[0].disconnect() return x d.addBoth(close) else: # We just place a marker command in the queue, and will fill in # the host and port numbers later (see generatePortCommand) portCmd = FTPCommand('PORT') # Ok, now we jump through a few hoops here. # This is the problem: a transfer is not to be trusted as complete # until we get both the "226 Transfer complete" message on the # control connection, and the data socket is closed. Thus, we use # a DeferredList to make sure we only fire the callback at the # right time. portCmd.transferDeferred = protocol.deferred portCmd.protocol = protocol portCmd.deferred.addErrback(portCmd.transferDeferred.errback) self.queueCommand(portCmd) # Create dummy functions for the next callback to call. # These will also be replaced with real functions in # generatePortCommand. portCmd.loseConnection = lambda result: result portCmd.fail = lambda error: error # Ensure that the connection always gets closed cmdsDeferred.addErrback(lambda e, pc=portCmd: pc.fail(e) or e) results = [cmdsDeferred, portCmd.deferred, portCmd.transferDeferred] d = defer.DeferredList(results, fireOnOneErrback=True, consumeErrors=True) d.addErrback(_unwrapFirstError) for cmd in cmds: self.queueCommand(cmd) return d
This method returns a DeferredList.
_openDataConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def generatePortCommand(self, portCmd): """ (Private) Generates the text of a given PORT command. """ # The problem is that we don't create the listening port until we need # it for various reasons, and so we have to muck about to figure out # what interface and port it's listening on, and then finally we can # create the text of the PORT command to send to the FTP server. # FIXME: This method is far too ugly. # FIXME: The best solution is probably to only create the data port # once per FTPClient, and just recycle it for each new download. # This should be ok, because we don't pipeline commands. # Start listening on a port factory = FTPDataPortFactory() factory.protocol = portCmd.protocol listener = reactor.listenTCP(0, factory) factory.port = listener # Ensure we close the listening port if something goes wrong def listenerFail(error, listener=listener): if listener.connected: listener.loseConnection() return error portCmd.fail = listenerFail # Construct crufty FTP magic numbers that represent host & port host = self.transport.getHost().host port = listener.getHost().port portCmd.text = 'PORT ' + encodeHostPort(host, port)
(Private) Generates the text of a given PORT command.
generatePortCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def escapePath(self, path): """ Returns a FTP escaped path (replace newlines with nulls). """ # Escape newline characters return path.replace('\n', '\0')
Returns a FTP escaped path (replace newlines with nulls).
escapePath
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def retrieveFile(self, path, protocol, offset=0): """ Retrieve a file from the given path This method issues the 'RETR' FTP command. The file is fed into the given Protocol instance. The data connection will be passive if self.passive is set. @param path: path to file that you wish to receive. @param protocol: a L{Protocol} instance. @param offset: offset to start downloading from @return: L{Deferred} """ cmds = ['RETR ' + self.escapePath(path)] if offset: cmds.insert(0, ('REST ' + str(offset))) return self.receiveFromConnection(cmds, protocol)
Retrieve a file from the given path This method issues the 'RETR' FTP command. The file is fed into the given Protocol instance. The data connection will be passive if self.passive is set. @param path: path to file that you wish to receive. @param protocol: a L{Protocol} instance. @param offset: offset to start downloading from @return: L{Deferred}
retrieveFile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def storeFile(self, path, offset=0): """ Store a file at the given path. This method issues the 'STOR' FTP command. @return: A tuple of two L{Deferred}s: - L{Deferred} L{IFinishableConsumer}. You must call the C{finish} method on the IFinishableConsumer when the file is completely transferred. - L{Deferred} list of control-connection responses. """ cmds = ['STOR ' + self.escapePath(path)] if offset: cmds.insert(0, ('REST ' + str(offset))) return self.sendToConnection(cmds)
Store a file at the given path. This method issues the 'STOR' FTP command. @return: A tuple of two L{Deferred}s: - L{Deferred} L{IFinishableConsumer}. You must call the C{finish} method on the IFinishableConsumer when the file is completely transferred. - L{Deferred} list of control-connection responses.
storeFile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def rename(self, pathFrom, pathTo): """ Rename a file. This method issues the I{RNFR}/I{RNTO} command sequence to rename C{pathFrom} to C{pathTo}. @param: pathFrom: the absolute path to the file to be renamed @type pathFrom: C{str} @param: pathTo: the absolute path to rename the file to. @type pathTo: C{str} @return: A L{Deferred} which fires when the rename operation has succeeded or failed. If it succeeds, the L{Deferred} is called back with a two-tuple of lists. The first list contains the responses to the I{RNFR} command. The second list contains the responses to the I{RNTO} command. If either I{RNFR} or I{RNTO} fails, the L{Deferred} is errbacked with L{CommandFailed} or L{BadResponse}. @rtype: L{Deferred} @since: 8.2 """ renameFrom = self.queueStringCommand('RNFR ' + self.escapePath(pathFrom)) renameTo = self.queueStringCommand('RNTO ' + self.escapePath(pathTo)) fromResponse = [] # Use a separate Deferred for the ultimate result so that Deferred # chaining can't interfere with its result. result = defer.Deferred() # Bundle up all the responses result.addCallback(lambda toResponse: (fromResponse, toResponse)) def ebFrom(failure): # Make sure the RNTO doesn't run if the RNFR failed. self.popCommandQueue() result.errback(failure) # Save the RNFR response to pass to the result Deferred later renameFrom.addCallbacks(fromResponse.extend, ebFrom) # Hook up the RNTO to the result Deferred as well renameTo.chainDeferred(result) return result
Rename a file. This method issues the I{RNFR}/I{RNTO} command sequence to rename C{pathFrom} to C{pathTo}. @param: pathFrom: the absolute path to the file to be renamed @type pathFrom: C{str} @param: pathTo: the absolute path to rename the file to. @type pathTo: C{str} @return: A L{Deferred} which fires when the rename operation has succeeded or failed. If it succeeds, the L{Deferred} is called back with a two-tuple of lists. The first list contains the responses to the I{RNFR} command. The second list contains the responses to the I{RNTO} command. If either I{RNFR} or I{RNTO} fails, the L{Deferred} is errbacked with L{CommandFailed} or L{BadResponse}. @rtype: L{Deferred} @since: 8.2
rename
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def list(self, path, protocol): """ Retrieve a file listing into the given protocol instance. This method issues the 'LIST' FTP command. @param path: path to get a file listing for. @param protocol: a L{Protocol} instance, probably a L{FTPFileListProtocol} instance. It can cope with most common file listing formats. @return: L{Deferred} """ if path is None: path = '' return self.receiveFromConnection(['LIST ' + self.escapePath(path)], protocol)
Retrieve a file listing into the given protocol instance. This method issues the 'LIST' FTP command. @param path: path to get a file listing for. @param protocol: a L{Protocol} instance, probably a L{FTPFileListProtocol} instance. It can cope with most common file listing formats. @return: L{Deferred}
list
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def nlst(self, path, protocol): """ Retrieve a short file listing into the given protocol instance. This method issues the 'NLST' FTP command. NLST (should) return a list of filenames, one per line. @param path: path to get short file listing for. @param protocol: a L{Protocol} instance. """ if path is None: path = '' return self.receiveFromConnection(['NLST ' + self.escapePath(path)], protocol)
Retrieve a short file listing into the given protocol instance. This method issues the 'NLST' FTP command. NLST (should) return a list of filenames, one per line. @param path: path to get short file listing for. @param protocol: a L{Protocol} instance.
nlst
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def cwd(self, path): """ Issues the CWD (Change Working Directory) command. @return: a L{Deferred} that will be called when done. """ return self.queueStringCommand('CWD ' + self.escapePath(path))
Issues the CWD (Change Working Directory) command. @return: a L{Deferred} that will be called when done.
cwd
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def makeDirectory(self, path): """ Make a directory This method issues the MKD command. @param path: The path to the directory to create. @type path: C{str} @return: A L{Deferred} which fires when the server responds. If the directory is created, the L{Deferred} is called back with the server response. If the server response indicates the directory was not created, the L{Deferred} is errbacked with a L{Failure} wrapping L{CommandFailed} or L{BadResponse}. @rtype: L{Deferred} @since: 8.2 """ return self.queueStringCommand('MKD ' + self.escapePath(path))
Make a directory This method issues the MKD command. @param path: The path to the directory to create. @type path: C{str} @return: A L{Deferred} which fires when the server responds. If the directory is created, the L{Deferred} is called back with the server response. If the server response indicates the directory was not created, the L{Deferred} is errbacked with a L{Failure} wrapping L{CommandFailed} or L{BadResponse}. @rtype: L{Deferred} @since: 8.2
makeDirectory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def removeFile(self, path): """ Delete a file on the server. L{removeFile} issues a I{DELE} command to the server to remove the indicated file. Note that this command cannot remove a directory. @param path: The path to the file to delete. May be relative to the current dir. @type path: C{str} @return: A L{Deferred} which fires when the server responds. On error, it is errbacked with either L{CommandFailed} or L{BadResponse}. On success, it is called back with a list of response lines. @rtype: L{Deferred} @since: 8.2 """ return self.queueStringCommand('DELE ' + self.escapePath(path))
Delete a file on the server. L{removeFile} issues a I{DELE} command to the server to remove the indicated file. Note that this command cannot remove a directory. @param path: The path to the file to delete. May be relative to the current dir. @type path: C{str} @return: A L{Deferred} which fires when the server responds. On error, it is errbacked with either L{CommandFailed} or L{BadResponse}. On success, it is called back with a list of response lines. @rtype: L{Deferred} @since: 8.2
removeFile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def removeDirectory(self, path): """ Delete a directory on the server. L{removeDirectory} issues a I{RMD} command to the server to remove the indicated directory. Described in RFC959. @param path: The path to the directory to delete. May be relative to the current working directory. @type path: C{str} @return: A L{Deferred} which fires when the server responds. On error, it is errbacked with either L{CommandFailed} or L{BadResponse}. On success, it is called back with a list of response lines. @rtype: L{Deferred} @since: 11.1 """ return self.queueStringCommand('RMD ' + self.escapePath(path))
Delete a directory on the server. L{removeDirectory} issues a I{RMD} command to the server to remove the indicated directory. Described in RFC959. @param path: The path to the directory to delete. May be relative to the current working directory. @type path: C{str} @return: A L{Deferred} which fires when the server responds. On error, it is errbacked with either L{CommandFailed} or L{BadResponse}. On success, it is called back with a list of response lines. @rtype: L{Deferred} @since: 11.1
removeDirectory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def cdup(self): """ Issues the CDUP (Change Directory UP) command. @return: a L{Deferred} that will be called when done. """ return self.queueStringCommand('CDUP')
Issues the CDUP (Change Directory UP) command. @return: a L{Deferred} that will be called when done.
cdup
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def pwd(self): """ Issues the PWD (Print Working Directory) command. The L{getDirectory} does the same job but automatically parses the result. @return: a L{Deferred} that will be called when done. It is up to the caller to interpret the response, but the L{parsePWDResponse} method in this module should work. """ return self.queueStringCommand('PWD')
Issues the PWD (Print Working Directory) command. The L{getDirectory} does the same job but automatically parses the result. @return: a L{Deferred} that will be called when done. It is up to the caller to interpret the response, but the L{parsePWDResponse} method in this module should work.
pwd
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def getDirectory(self): """ Returns the current remote directory. @return: a L{Deferred} that will be called back with a C{str} giving the remote directory or which will errback with L{CommandFailed} if an error response is returned. """ def cbParse(result): try: # The only valid code is 257 if int(result[0].split(' ', 1)[0]) != 257: raise ValueError except (IndexError, ValueError): return failure.Failure(CommandFailed(result)) path = parsePWDResponse(result[0]) if path is None: return failure.Failure(CommandFailed(result)) return path return self.pwd().addCallback(cbParse)
Returns the current remote directory. @return: a L{Deferred} that will be called back with a C{str} giving the remote directory or which will errback with L{CommandFailed} if an error response is returned.
getDirectory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def quit(self): """ Issues the I{QUIT} command. @return: A L{Deferred} that fires when the server acknowledges the I{QUIT} command. The transport should not be disconnected until this L{Deferred} fires. """ return self.queueStringCommand('QUIT')
Issues the I{QUIT} command. @return: A L{Deferred} that fires when the server acknowledges the I{QUIT} command. The transport should not be disconnected until this L{Deferred} fires.
quit
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def parseDirectoryLine(self, line): """ Return a dictionary of fields, or None if line cannot be parsed. @param line: line of text expected to contain a directory entry @type line: str @return: dict """ match = self.fileLinePattern.match(line) if match is None: return None else: d = match.groupdict() d['filename'] = d['filename'].replace(r'\ ', ' ') d['nlinks'] = int(d['nlinks']) d['size'] = int(d['size']) if d['linktarget']: d['linktarget'] = d['linktarget'].replace(r'\ ', ' ') return d
Return a dictionary of fields, or None if line cannot be parsed. @param line: line of text expected to contain a directory entry @type line: str @return: dict
parseDirectoryLine
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def addFile(self, info): """ Append file information dictionary to the list of known files. Subclasses can override or extend this method to handle file information differently without affecting the parsing of data from the server. @param info: dictionary containing the parsed representation of the file information @type info: dict """ self.files.append(info)
Append file information dictionary to the list of known files. Subclasses can override or extend this method to handle file information differently without affecting the parsing of data from the server. @param info: dictionary containing the parsed representation of the file information @type info: dict
addFile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def unknownLine(self, line): """ Deal with received lines which could not be parsed as file information. Subclasses can override this to perform any special processing needed. @param line: unparsable line as received @type line: str """ pass
Deal with received lines which could not be parsed as file information. Subclasses can override this to perform any special processing needed. @param line: unparsable line as received @type line: str
unknownLine
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def parsePWDResponse(response): """ Returns the path from a response to a PWD command. Responses typically look like:: 257 "/home/andrew" is current directory. For this example, I will return C{'/home/andrew'}. If I can't find the path, I return L{None}. """ match = re.search('"(.*)"', response) if match: return match.groups()[0] else: return None
Returns the path from a response to a PWD command. Responses typically look like:: 257 "/home/andrew" is current directory. For this example, I will return C{'/home/andrew'}. If I can't find the path, I return L{None}.
parsePWDResponse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ftp.py
MIT
def _wrappedLogPrefix(wrapper, wrapped): """ Compute a log prefix for a wrapper and the object it wraps. @rtype: C{str} """ if ILoggingContext.providedBy(wrapped): logPrefix = wrapped.logPrefix() else: logPrefix = wrapped.__class__.__name__ return "%s (%s)" % (logPrefix, wrapper.__class__.__name__)
Compute a log prefix for a wrapper and the object it wraps. @rtype: C{str}
_wrappedLogPrefix
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def logPrefix(self): """ Use a customized log prefix mentioning both the wrapped protocol and the current one. """ return _wrappedLogPrefix(self, self.wrappedProtocol)
Use a customized log prefix mentioning both the wrapped protocol and the current one.
logPrefix
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def makeConnection(self, transport): """ When a connection is made, register this wrapper with its factory, save the real transport, and connect the wrapped protocol to this L{ProtocolWrapper} to intercept any transport calls it makes. """ directlyProvides(self, providedBy(transport)) Protocol.makeConnection(self, transport) self.factory.registerProtocol(self) self.wrappedProtocol.makeConnection(self)
When a connection is made, register this wrapper with its factory, save the real transport, and connect the wrapped protocol to this L{ProtocolWrapper} to intercept any transport calls it makes.
makeConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def logPrefix(self): """ Generate a log prefix mentioning both the wrapped factory and this one. """ return _wrappedLogPrefix(self, self.wrappedFactory)
Generate a log prefix mentioning both the wrapped factory and this one.
logPrefix
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def registerProtocol(self, p): """ Called by protocol to register itself. """ self.protocols[p] = 1
Called by protocol to register itself.
registerProtocol
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def unregisterProtocol(self, p): """ Called by protocols when they go away. """ del self.protocols[p]
Called by protocols when they go away.
unregisterProtocol
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def callLater(self, period, func): """ Wrapper around L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>} for test purpose. """ from twisted.internet import reactor return reactor.callLater(period, func)
Wrapper around L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>} for test purpose.
callLater
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def registerWritten(self, length): """ Called by protocol to tell us more bytes were written. """ self.writtenThisSecond += length
Called by protocol to tell us more bytes were written.
registerWritten
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def registerRead(self, length): """ Called by protocol to tell us more bytes were read. """ self.readThisSecond += length
Called by protocol to tell us more bytes were read.
registerRead
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def checkReadBandwidth(self): """ Checks if we've passed bandwidth limits. """ if self.readThisSecond > self.readLimit: self.throttleReads() throttleTime = (float(self.readThisSecond) / self.readLimit) - 1.0 self.unthrottleReadsID = self.callLater(throttleTime, self.unthrottleReads) self.readThisSecond = 0 self.checkReadBandwidthID = self.callLater(1, self.checkReadBandwidth)
Checks if we've passed bandwidth limits.
checkReadBandwidth
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def throttleReads(self): """ Throttle reads on all protocols. """ log.msg("Throttling reads on %s" % self) for p in self.protocols.keys(): p.throttleReads()
Throttle reads on all protocols.
throttleReads
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def unthrottleReads(self): """ Stop throttling reads on all protocols. """ self.unthrottleReadsID = None log.msg("Stopped throttling reads on %s" % self) for p in self.protocols.keys(): p.unthrottleReads()
Stop throttling reads on all protocols.
unthrottleReads
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def throttleWrites(self): """ Throttle writes on all protocols. """ log.msg("Throttling writes on %s" % self) for p in self.protocols.keys(): p.throttleWrites()
Throttle writes on all protocols.
throttleWrites
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def unthrottleWrites(self): """ Stop throttling writes on all protocols. """ self.unthrottleWritesID = None log.msg("Stopped throttling writes on %s" % self) for p in self.protocols.keys(): p.unthrottleWrites()
Stop throttling writes on all protocols.
unthrottleWrites
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def __init__(self, factory, wrappedProtocol, timeoutPeriod): """ Constructor. @param factory: An L{TimeoutFactory}. @param wrappedProtocol: A L{Protocol} to wrapp. @param timeoutPeriod: Number of seconds to wait for activity before timing out. """ ProtocolWrapper.__init__(self, factory, wrappedProtocol) self.timeoutCall = None self.timeoutPeriod = None self.setTimeout(timeoutPeriod)
Constructor. @param factory: An L{TimeoutFactory}. @param wrappedProtocol: A L{Protocol} to wrapp. @param timeoutPeriod: Number of seconds to wait for activity before timing out.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def setTimeout(self, timeoutPeriod=None): """ Set a timeout. This will cancel any existing timeouts. @param timeoutPeriod: If not L{None}, change the timeout period. Otherwise, use the existing value. """ self.cancelTimeout() self.timeoutPeriod = timeoutPeriod if timeoutPeriod is not None: self.timeoutCall = self.factory.callLater(self.timeoutPeriod, self.timeoutFunc)
Set a timeout. This will cancel any existing timeouts. @param timeoutPeriod: If not L{None}, change the timeout period. Otherwise, use the existing value.
setTimeout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def cancelTimeout(self): """ Cancel the timeout. If the timeout was already cancelled, this does nothing. """ self.timeoutPeriod = None if self.timeoutCall: try: self.timeoutCall.cancel() except (error.AlreadyCalled, error.AlreadyCancelled): pass self.timeoutCall = None
Cancel the timeout. If the timeout was already cancelled, this does nothing.
cancelTimeout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def resetTimeout(self): """ Reset the timeout, usually because some activity just happened. """ if self.timeoutCall: self.timeoutCall.reset(self.timeoutPeriod)
Reset the timeout, usually because some activity just happened.
resetTimeout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def timeoutFunc(self): """ This method is called when the timeout is triggered. By default it calls I{loseConnection}. Override this if you want something else to happen. """ self.loseConnection()
This method is called when the timeout is triggered. By default it calls I{loseConnection}. Override this if you want something else to happen.
timeoutFunc
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def callLater(self, period, func): """ Wrapper around L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>} for test purpose. """ from twisted.internet import reactor return reactor.callLater(period, func)
Wrapper around L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>} for test purpose.
callLater
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def __init__(self, factory, wrappedProtocol, logfile, lengthLimit=None, number=0): """ @param factory: factory which created this protocol. @type factory: L{protocol.Factory}. @param wrappedProtocol: the underlying protocol. @type wrappedProtocol: C{protocol.Protocol}. @param logfile: file opened for writing used to write log messages. @type logfile: C{file} @param lengthLimit: maximum size of the datareceived logged. @type lengthLimit: C{int} @param number: identifier of the connection. @type number: C{int}. """ ProtocolWrapper.__init__(self, factory, wrappedProtocol) self.logfile = logfile self.lengthLimit = lengthLimit self._number = number
@param factory: factory which created this protocol. @type factory: L{protocol.Factory}. @param wrappedProtocol: the underlying protocol. @type wrappedProtocol: C{protocol.Protocol}. @param logfile: file opened for writing used to write log messages. @type logfile: C{file} @param lengthLimit: maximum size of the datareceived logged. @type lengthLimit: C{int} @param number: identifier of the connection. @type number: C{int}.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def resetCounter(self): """ Reset the value of the counter used to identify connections. """ self._counter = 0
Reset the value of the counter used to identify connections.
resetCounter
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def callLater(self, period, func): """ Wrapper around L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>} for test purpose. """ from twisted.internet import reactor return reactor.callLater(period, func)
Wrapper around L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>} for test purpose.
callLater
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def resetTimeout(self): """ Reset the timeout count down. If the connection has already timed out, then do nothing. If the timeout has been cancelled (probably using C{setTimeout(None)}), also do nothing. It's often a good idea to call this when the protocol has received some meaningful input from the other end of the connection. "I've got some data, they're still there, reset the timeout". """ if self.__timeoutCall is not None and self.timeOut is not None: self.__timeoutCall.reset(self.timeOut)
Reset the timeout count down. If the connection has already timed out, then do nothing. If the timeout has been cancelled (probably using C{setTimeout(None)}), also do nothing. It's often a good idea to call this when the protocol has received some meaningful input from the other end of the connection. "I've got some data, they're still there, reset the timeout".
resetTimeout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def setTimeout(self, period): """ Change the timeout period @type period: C{int} or L{None} @param period: The period, in seconds, to change the timeout to, or L{None} to disable the timeout. """ prev = self.timeOut self.timeOut = period if self.__timeoutCall is not None: if period is None: try: self.__timeoutCall.cancel() except (error.AlreadyCancelled, error.AlreadyCalled): # Do nothing if the call was already consumed. pass self.__timeoutCall = None else: self.__timeoutCall.reset(period) elif period is not None: self.__timeoutCall = self.callLater(period, self.__timedOut) return prev
Change the timeout period @type period: C{int} or L{None} @param period: The period, in seconds, to change the timeout to, or L{None} to disable the timeout.
setTimeout
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def timeoutConnection(self): """ Called when the connection times out. Override to define behavior other than dropping the connection. """ self.transport.loseConnection()
Called when the connection times out. Override to define behavior other than dropping the connection.
timeoutConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/policies.py
MIT
def validQuery(self, portOnServer, portOnClient): """ Called when a valid query is received to look up and deliver the response. @param portOnServer: The server port from the query. @param portOnClient: The client port from the query. """ serverAddr = self.transport.getHost().host, portOnServer clientAddr = self.transport.getPeer().host, portOnClient defer.maybeDeferred(self.lookup, serverAddr, clientAddr ).addCallback(self._cbLookup, portOnServer, portOnClient ).addErrback(self._ebLookup, portOnServer, portOnClient )
Called when a valid query is received to look up and deliver the response. @param portOnServer: The server port from the query. @param portOnClient: The client port from the query.
validQuery
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ident.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ident.py
MIT
def lookup(self, serverAddress, clientAddress): """ Lookup user information about the specified address pair. Return value should be a two-tuple of system name and username. Acceptable values for the system name may be found online at:: U{http://www.iana.org/assignments/operating-system-names} This method may also raise any IdentError subclass (or IdentError itself) to indicate user information will not be provided for the given query. A Deferred may also be returned. @param serverAddress: A two-tuple representing the server endpoint of the address being queried. The first element is a string holding a dotted-quad IP address. The second element is an integer representing the port. @param clientAddress: Like I{serverAddress}, but represents the client endpoint of the address being queried. """ raise IdentError()
Lookup user information about the specified address pair. Return value should be a two-tuple of system name and username. Acceptable values for the system name may be found online at:: U{http://www.iana.org/assignments/operating-system-names} This method may also raise any IdentError subclass (or IdentError itself) to indicate user information will not be provided for the given query. A Deferred may also be returned. @param serverAddress: A two-tuple representing the server endpoint of the address being queried. The first element is a string holding a dotted-quad IP address. The second element is an integer representing the port. @param clientAddress: Like I{serverAddress}, but represents the client endpoint of the address being queried.
lookup
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ident.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ident.py
MIT
def lookup(self, portOnServer, portOnClient): """ Lookup user information about the specified address pair. """ self.queries.append((defer.Deferred(), portOnServer, portOnClient)) if len(self.queries) > 1: return self.queries[-1][0] self.sendLine('%d, %d' % (portOnServer, portOnClient)) return self.queries[-1][0]
Lookup user information about the specified address pair.
lookup
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ident.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/ident.py
MIT
def __init__(self, parentBucket=None): """ Create a L{Bucket} that may have a parent L{Bucket}. @param parentBucket: If a parent Bucket is specified, all L{add} and L{drip} operations on this L{Bucket} will be applied on the parent L{Bucket} as well. @type parentBucket: L{Bucket} """ self.content = 0 self.parentBucket = parentBucket self.lastDrip = time()
Create a L{Bucket} that may have a parent L{Bucket}. @param parentBucket: If a parent Bucket is specified, all L{add} and L{drip} operations on this L{Bucket} will be applied on the parent L{Bucket} as well. @type parentBucket: L{Bucket}
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
MIT
def add(self, amount): """ Adds tokens to the L{Bucket} and its C{parentBucket}. This will add as many of the C{amount} tokens as will fit into both this L{Bucket} and its C{parentBucket}. @param amount: The number of tokens to try to add. @type amount: C{int} @returns: The number of tokens that actually fit. @returntype: C{int} """ self.drip() if self.maxburst is None: allowable = amount else: allowable = min(amount, self.maxburst - self.content) if self.parentBucket is not None: allowable = self.parentBucket.add(allowable) self.content += allowable return allowable
Adds tokens to the L{Bucket} and its C{parentBucket}. This will add as many of the C{amount} tokens as will fit into both this L{Bucket} and its C{parentBucket}. @param amount: The number of tokens to try to add. @type amount: C{int} @returns: The number of tokens that actually fit. @returntype: C{int}
add
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
MIT
def drip(self): """ Let some of the bucket drain. The L{Bucket} drains at the rate specified by the class variable C{rate}. @returns: C{True} if the bucket is empty after this drip. @returntype: C{bool} """ if self.parentBucket is not None: self.parentBucket.drip() if self.rate is None: self.content = 0 else: now = time() deltaTime = now - self.lastDrip deltaTokens = deltaTime * self.rate self.content = max(0, self.content - deltaTokens) self.lastDrip = now return self.content == 0
Let some of the bucket drain. The L{Bucket} drains at the rate specified by the class variable C{rate}. @returns: C{True} if the bucket is empty after this drip. @returntype: C{bool}
drip
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
MIT
def getBucketFor(*somethings, **some_kw): """ Return a L{Bucket} corresponding to the provided parameters. @returntype: L{Bucket} """
Return a L{Bucket} corresponding to the provided parameters. @returntype: L{Bucket}
getBucketFor
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
MIT
def getBucketFor(self, *a, **kw): """ Find or create a L{Bucket} corresponding to the provided parameters. Any parameters are passed on to L{getBucketKey}, from them it decides which bucket you get. @returntype: L{Bucket} """ if ((self.sweepInterval is not None) and ((time() - self.lastSweep) > self.sweepInterval)): self.sweep() if self.parentFilter: parentBucket = self.parentFilter.getBucketFor(self, *a, **kw) else: parentBucket = None key = self.getBucketKey(*a, **kw) bucket = self.buckets.get(key) if bucket is None: bucket = self.bucketFactory(parentBucket) self.buckets[key] = bucket return bucket
Find or create a L{Bucket} corresponding to the provided parameters. Any parameters are passed on to L{getBucketKey}, from them it decides which bucket you get. @returntype: L{Bucket}
getBucketFor
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
MIT
def getBucketKey(self, *a, **kw): """ Construct a key based on the input parameters to choose a L{Bucket}. The default implementation returns the same key for all arguments. Override this method to provide L{Bucket} selection. @returns: Something to be used as a key in the bucket cache. """ return None
Construct a key based on the input parameters to choose a L{Bucket}. The default implementation returns the same key for all arguments. Override this method to provide L{Bucket} selection. @returns: Something to be used as a key in the bucket cache.
getBucketKey
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
MIT
def sweep(self): """ Remove empty buckets. """ for key, bucket in self.buckets.items(): bucket_is_empty = bucket.drip() if (bucket._refcount == 0) and bucket_is_empty: del self.buckets[key] self.lastSweep = time()
Remove empty buckets.
sweep
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
MIT
def __init__(self, protoClass, bucketFilter): """ Tell me what to wrap and where to get buckets. @param protoClass: The class of C{Protocol} this will generate wrapped instances of. @type protoClass: L{Protocol<twisted.internet.interfaces.IProtocol>} class @param bucketFilter: The filter which will determine how traffic is shaped. @type bucketFilter: L{HierarchicalBucketFilter}. """ # More precisely, protoClass can be any callable that will return # instances of something that implements IProtocol. self.protocol = protoClass self.bucketFilter = bucketFilter
Tell me what to wrap and where to get buckets. @param protoClass: The class of C{Protocol} this will generate wrapped instances of. @type protoClass: L{Protocol<twisted.internet.interfaces.IProtocol>} class @param bucketFilter: The filter which will determine how traffic is shaped. @type bucketFilter: L{HierarchicalBucketFilter}.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
MIT
def __call__(self, *a, **kw): """ Make a C{Protocol} instance with a shaped transport. Any parameters will be passed on to the protocol's initializer. @returns: A C{Protocol} instance with a L{ShapedTransport}. """ proto = self.protocol(*a, **kw) origMakeConnection = proto.makeConnection def makeConnection(transport): bucket = self.bucketFilter.getBucketFor(transport) shapedTransport = ShapedTransport(transport, bucket) return origMakeConnection(shapedTransport) proto.makeConnection = makeConnection return proto
Make a C{Protocol} instance with a shaped transport. Any parameters will be passed on to the protocol's initializer. @returns: A C{Protocol} instance with a L{ShapedTransport}.
__call__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/htb.py
MIT
def sendCode(self, code, message=b''): """ Send an SMTP-like code with a message. """ self.sendLine(str(code).encode("ascii") + b' ' + message)
Send an SMTP-like code with a message.
sendCode
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/postfix.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/postfix.py
MIT
def convertError(sourceType, targetType): """ Convert an error into a different error type. @param sourceType: The type of exception that should be caught and converted. @type sourceType: L{Exception} @param targetType: The type of exception to which the original should be converted. @type targetType: L{Exception} """ try: yield None except sourceType: compat.reraise(targetType(), sys.exc_info()[-1])
Convert an error into a different error type. @param sourceType: The type of exception that should be caught and converted. @type sourceType: L{Exception} @param targetType: The type of exception to which the original should be converted. @type targetType: L{Exception}
convertError
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_exceptions.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_exceptions.py
MIT
def feed(self, data): """ Consume a chunk of data and attempt to parse it. @param data: A bytestring. @type data: bytes @return: A two-tuple containing, in order, a L{_interfaces.IProxyInfo} and any bytes fed to the parser that followed the end of the header. Both of these values are None until a complete header is parsed. @raises InvalidProxyHeader: If the bytes fed to the parser create an invalid PROXY header. """ self.buffer += data if len(self.buffer) < 16: raise InvalidProxyHeader() size = struct.unpack('!H', self.buffer[14:16])[0] + 16 if len(self.buffer) < size: return (None, None) header, remaining = self.buffer[:size], self.buffer[size:] self.buffer = b'' info = self.parse(header) return (info, remaining)
Consume a chunk of data and attempt to parse it. @param data: A bytestring. @type data: bytes @return: A two-tuple containing, in order, a L{_interfaces.IProxyInfo} and any bytes fed to the parser that followed the end of the header. Both of these values are None until a complete header is parsed. @raises InvalidProxyHeader: If the bytes fed to the parser create an invalid PROXY header.
feed
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v2parser.py
MIT
def _bytesToIPv4(bytestring): """ Convert packed 32-bit IPv4 address bytes into a dotted-quad ASCII bytes representation of that address. @param bytestring: 4 octets representing an IPv4 address. @type bytestring: L{bytes} @return: a dotted-quad notation IPv4 address. @rtype: L{bytes} """ return b'.'.join( ('%i' % (ord(b),)).encode('ascii') for b in compat.iterbytes(bytestring) )
Convert packed 32-bit IPv4 address bytes into a dotted-quad ASCII bytes representation of that address. @param bytestring: 4 octets representing an IPv4 address. @type bytestring: L{bytes} @return: a dotted-quad notation IPv4 address. @rtype: L{bytes}
_bytesToIPv4
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v2parser.py
MIT
def _bytesToIPv6(bytestring): """ Convert packed 128-bit IPv6 address bytes into a colon-separated ASCII bytes representation of that address. @param bytestring: 16 octets representing an IPv6 address. @type bytestring: L{bytes} @return: a dotted-quad notation IPv6 address. @rtype: L{bytes} """ hexString = binascii.b2a_hex(bytestring) return b':'.join( ('%x' % (int(hexString[b:b+4], 16),)).encode('ascii') for b in range(0, 32, 4) )
Convert packed 128-bit IPv6 address bytes into a colon-separated ASCII bytes representation of that address. @param bytestring: 16 octets representing an IPv6 address. @type bytestring: L{bytes} @return: a dotted-quad notation IPv6 address. @rtype: L{bytes}
_bytesToIPv6
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v2parser.py
MIT
def parse(cls, line): """ Parse a bytestring as a full PROXY protocol header. @param line: A bytestring that represents a valid HAProxy PROXY protocol version 2 header. @type line: bytes @return: A L{_interfaces.IProxyInfo} containing the parsed data. @raises InvalidProxyHeader: If the bytestring does not represent a valid PROXY header. """ prefix = line[:12] addrInfo = None with convertError(IndexError, InvalidProxyHeader): # Use single value slices to ensure bytestring values are returned # instead of int in PY3. versionCommand = ord(line[12:13]) familyProto = ord(line[13:14]) if prefix != cls.PREFIX: raise InvalidProxyHeader() version, command = versionCommand & _HIGH, versionCommand & _LOW if version not in cls.VERSIONS or command not in cls.COMMANDS: raise InvalidProxyHeader() if cls.COMMANDS[command] == _LOCALCOMMAND: return _info.ProxyInfo(line, None, None) family, netproto = familyProto & _HIGH, familyProto & _LOW with convertError(ValueError, InvalidNetworkProtocol): family = NetFamily.lookupByValue(family) netproto = NetProtocol.lookupByValue(netproto) if ( family is NetFamily.UNSPEC or netproto is NetProtocol.UNSPEC ): return _info.ProxyInfo(line, None, None) addressFormat = cls.ADDRESSFORMATS[familyProto] addrInfo = line[16:16+struct.calcsize(addressFormat)] if family is NetFamily.UNIX: with convertError(struct.error, MissingAddressData): source, dest = struct.unpack(addressFormat, addrInfo) return _info.ProxyInfo( line, address.UNIXAddress(source.rstrip(b'\x00')), address.UNIXAddress(dest.rstrip(b'\x00')), ) addrType = 'TCP' if netproto is NetProtocol.DGRAM: addrType = 'UDP' addrCls = address.IPv4Address addrParser = cls._bytesToIPv4 if family is NetFamily.INET6: addrCls = address.IPv6Address addrParser = cls._bytesToIPv6 with convertError(struct.error, MissingAddressData): info = struct.unpack(addressFormat, addrInfo) source, dest, sPort, dPort = info return _info.ProxyInfo( line, addrCls(addrType, addrParser(source), sPort), addrCls(addrType, addrParser(dest), dPort), )
Parse a bytestring as a full PROXY protocol header. @param line: A bytestring that represents a valid HAProxy PROXY protocol version 2 header. @type line: bytes @return: A L{_interfaces.IProxyInfo} containing the parsed data. @raises InvalidProxyHeader: If the bytestring does not represent a valid PROXY header.
parse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v2parser.py
MIT
def feed(self, data): """ Consume a chunk of data and attempt to parse it. @param data: A bytestring. @type data: bytes @return: A two-tuple containing, in order, an L{IProxyInfo} and any bytes fed to the parser that followed the end of the header. Both of these values are None until a complete header is parsed. @raises InvalidProxyHeader: If the bytes fed to the parser create an invalid PROXY header. """
Consume a chunk of data and attempt to parse it. @param data: A bytestring. @type data: bytes @return: A two-tuple containing, in order, an L{IProxyInfo} and any bytes fed to the parser that followed the end of the header. Both of these values are None until a complete header is parsed. @raises InvalidProxyHeader: If the bytes fed to the parser create an invalid PROXY header.
feed
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_interfaces.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_interfaces.py
MIT
def parse(self, line): """ Parse a bytestring as a full PROXY protocol header line. @param line: A bytestring that represents a valid HAProxy PROXY protocol header line. @type line: bytes @return: An L{IProxyInfo} containing the parsed data. @raises InvalidProxyHeader: If the bytestring does not represent a valid PROXY header. """
Parse a bytestring as a full PROXY protocol header line. @param line: A bytestring that represents a valid HAProxy PROXY protocol header line. @type line: bytes @return: An L{IProxyInfo} containing the parsed data. @raises InvalidProxyHeader: If the bytestring does not represent a valid PROXY header.
parse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_interfaces.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_interfaces.py
MIT
def feed(self, data): """ Consume a chunk of data and attempt to parse it. @param data: A bytestring. @type data: L{bytes} @return: A two-tuple containing, in order, a L{_interfaces.IProxyInfo} and any bytes fed to the parser that followed the end of the header. Both of these values are None until a complete header is parsed. @raises InvalidProxyHeader: If the bytes fed to the parser create an invalid PROXY header. """ self.buffer += data if len(self.buffer) > 107 and self.NEWLINE not in self.buffer: raise InvalidProxyHeader() lines = (self.buffer).split(self.NEWLINE, 1) if not len(lines) > 1: return (None, None) self.buffer = b'' remaining = lines.pop() header = lines.pop() info = self.parse(header) return (info, remaining)
Consume a chunk of data and attempt to parse it. @param data: A bytestring. @type data: L{bytes} @return: A two-tuple containing, in order, a L{_interfaces.IProxyInfo} and any bytes fed to the parser that followed the end of the header. Both of these values are None until a complete header is parsed. @raises InvalidProxyHeader: If the bytes fed to the parser create an invalid PROXY header.
feed
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v1parser.py
MIT
def parse(cls, line): """ Parse a bytestring as a full PROXY protocol header line. @param line: A bytestring that represents a valid HAProxy PROXY protocol header line. @type line: bytes @return: A L{_interfaces.IProxyInfo} containing the parsed data. @raises InvalidProxyHeader: If the bytestring does not represent a valid PROXY header. @raises InvalidNetworkProtocol: When no protocol can be parsed or is not one of the allowed values. @raises MissingAddressData: When the protocol is TCP* but the header does not contain a complete set of addresses and ports. """ originalLine = line proxyStr = None networkProtocol = None sourceAddr = None sourcePort = None destAddr = None destPort = None with convertError(ValueError, InvalidProxyHeader): proxyStr, line = line.split(b' ', 1) if proxyStr != cls.PROXYSTR: raise InvalidProxyHeader() with convertError(ValueError, InvalidNetworkProtocol): networkProtocol, line = line.split(b' ', 1) if networkProtocol not in cls.ALLOWED_NET_PROTOS: raise InvalidNetworkProtocol() if networkProtocol == cls.UNKNOWN_PROTO: return _info.ProxyInfo(originalLine, None, None) with convertError(ValueError, MissingAddressData): sourceAddr, line = line.split(b' ', 1) with convertError(ValueError, MissingAddressData): destAddr, line = line.split(b' ', 1) with convertError(ValueError, MissingAddressData): sourcePort, line = line.split(b' ', 1) with convertError(ValueError, MissingAddressData): destPort = line.split(b' ')[0] if networkProtocol == cls.TCP4_PROTO: return _info.ProxyInfo( originalLine, address.IPv4Address('TCP', sourceAddr, int(sourcePort)), address.IPv4Address('TCP', destAddr, int(destPort)), ) return _info.ProxyInfo( originalLine, address.IPv6Address('TCP', sourceAddr, int(sourcePort)), address.IPv6Address('TCP', destAddr, int(destPort)), )
Parse a bytestring as a full PROXY protocol header line. @param line: A bytestring that represents a valid HAProxy PROXY protocol header line. @type line: bytes @return: A L{_interfaces.IProxyInfo} containing the parsed data. @raises InvalidProxyHeader: If the bytestring does not represent a valid PROXY header. @raises InvalidNetworkProtocol: When no protocol can be parsed or is not one of the allowed values. @raises MissingAddressData: When the protocol is TCP* but the header does not contain a complete set of addresses and ports.
parse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_v1parser.py
MIT
def logPrefix(self): """ Annotate the wrapped factory's log prefix with some text indicating the PROXY protocol is in use. @rtype: C{str} """ if interfaces.ILoggingContext.providedBy(self.wrappedFactory): logPrefix = self.wrappedFactory.logPrefix() else: logPrefix = self.wrappedFactory.__class__.__name__ return "%s (PROXY)" % (logPrefix,)
Annotate the wrapped factory's log prefix with some text indicating the PROXY protocol is in use. @rtype: C{str}
logPrefix
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_wrapper.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_wrapper.py
MIT
def proxyEndpoint(wrappedEndpoint): """ Wrap an endpoint with PROXY protocol support, so that the transport's C{getHost} and C{getPeer} methods reflect the attributes of the proxied connection rather than the underlying connection. @param wrappedEndpoint: The underlying listening endpoint. @type wrappedEndpoint: L{IStreamServerEndpoint} @return: a new listening endpoint that speaks the PROXY protocol. @rtype: L{IStreamServerEndpoint} """ return _WrapperServerEndpoint(wrappedEndpoint, HAProxyWrappingFactory)
Wrap an endpoint with PROXY protocol support, so that the transport's C{getHost} and C{getPeer} methods reflect the attributes of the proxied connection rather than the underlying connection. @param wrappedEndpoint: The underlying listening endpoint. @type wrappedEndpoint: L{IStreamServerEndpoint} @return: a new listening endpoint that speaks the PROXY protocol. @rtype: L{IStreamServerEndpoint}
proxyEndpoint
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_wrapper.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_wrapper.py
MIT
def unparseEndpoint(args, kwargs): """ Un-parse the already-parsed args and kwargs back into endpoint syntax. @param args: C{:}-separated arguments @type args: L{tuple} of native L{str} @param kwargs: C{:} and then C{=}-separated keyword arguments @type arguments: L{tuple} of native L{str} @return: a string equivalent to the original format which this was parsed as. @rtype: native L{str} """ description = ':'.join( [quoteStringArgument(str(arg)) for arg in args] + sorted(['%s=%s' % (quoteStringArgument(str(key)), quoteStringArgument(str(value))) for key, value in iteritems(kwargs) ])) return description
Un-parse the already-parsed args and kwargs back into endpoint syntax. @param args: C{:}-separated arguments @type args: L{tuple} of native L{str} @param kwargs: C{:} and then C{=}-separated keyword arguments @type arguments: L{tuple} of native L{str} @return: a string equivalent to the original format which this was parsed as. @rtype: native L{str}
unparseEndpoint
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_parser.py
MIT
def parseStreamServer(self, reactor, *args, **kwargs): """ Parse a stream server endpoint from a reactor and string-only arguments and keyword arguments. @param reactor: The reactor. @param args: The parsed string arguments. @param kwargs: The parsed keyword arguments. @return: a stream server endpoint @rtype: L{IStreamServerEndpoint} """ subdescription = unparseEndpoint(args, kwargs) wrappedEndpoint = serverFromString(reactor, subdescription) return proxyEndpoint(wrappedEndpoint)
Parse a stream server endpoint from a reactor and string-only arguments and keyword arguments. @param reactor: The reactor. @param args: The parsed string arguments. @param kwargs: The parsed keyword arguments. @return: a stream server endpoint @rtype: L{IStreamServerEndpoint}
parseStreamServer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/_parser.py
MIT
def test_missingPROXYHeaderValue(self): """ Test that an exception is raised when the PROXY header is missing. """ self.assertRaises( InvalidProxyHeader, _v1parser.V1Parser.parse, b'NOTPROXY ', )
Test that an exception is raised when the PROXY header is missing.
test_missingPROXYHeaderValue
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
MIT
def test_invalidNetworkProtocol(self): """ Test that an exception is raised when the proto is not TCP or UNKNOWN. """ self.assertRaises( InvalidNetworkProtocol, _v1parser.V1Parser.parse, b'PROXY WUTPROTO ', )
Test that an exception is raised when the proto is not TCP or UNKNOWN.
test_invalidNetworkProtocol
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
MIT
def test_missingSourceData(self): """ Test that an exception is raised when the proto has no source data. """ self.assertRaises( MissingAddressData, _v1parser.V1Parser.parse, b'PROXY TCP4 ', )
Test that an exception is raised when the proto has no source data.
test_missingSourceData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
MIT
def test_missingDestData(self): """ Test that an exception is raised when the proto has no destination. """ self.assertRaises( MissingAddressData, _v1parser.V1Parser.parse, b'PROXY TCP4 127.0.0.1 8080 8888', )
Test that an exception is raised when the proto has no destination.
test_missingDestData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
MIT
def test_fullParsingSuccess(self): """ Test that parsing is successful for a PROXY header. """ info = _v1parser.V1Parser.parse( b'PROXY TCP4 127.0.0.1 127.0.0.1 8080 8888', ) self.assertIsInstance(info.source, address.IPv4Address) self.assertEqual(info.source.host, b'127.0.0.1') self.assertEqual(info.source.port, 8080) self.assertEqual(info.destination.host, b'127.0.0.1') self.assertEqual(info.destination.port, 8888)
Test that parsing is successful for a PROXY header.
test_fullParsingSuccess
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
MIT
def test_fullParsingSuccess_IPv6(self): """ Test that parsing is successful for an IPv6 PROXY header. """ info = _v1parser.V1Parser.parse( b'PROXY TCP6 ::1 ::1 8080 8888', ) self.assertIsInstance(info.source, address.IPv6Address) self.assertEqual(info.source.host, b'::1') self.assertEqual(info.source.port, 8080) self.assertEqual(info.destination.host, b'::1') self.assertEqual(info.destination.port, 8888)
Test that parsing is successful for an IPv6 PROXY header.
test_fullParsingSuccess_IPv6
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
MIT
def test_fullParsingSuccess_UNKNOWN(self): """ Test that parsing is successful for a UNKNOWN PROXY header. """ info = _v1parser.V1Parser.parse( b'PROXY UNKNOWN anything could go here', ) self.assertIsNone(info.source) self.assertIsNone(info.destination)
Test that parsing is successful for a UNKNOWN PROXY header.
test_fullParsingSuccess_UNKNOWN
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
MIT
def test_feedParsing(self): """ Test that parsing happens when fed a complete line. """ parser = _v1parser.V1Parser() info, remaining = parser.feed(b'PROXY TCP4 127.0.0.1 127.0.0.1 ') self.assertFalse(info) self.assertFalse(remaining) info, remaining = parser.feed(b'8080 8888') self.assertFalse(info) self.assertFalse(remaining) info, remaining = parser.feed(b'\r\n') self.assertFalse(remaining) self.assertIsInstance(info.source, address.IPv4Address) self.assertEqual(info.source.host, b'127.0.0.1') self.assertEqual(info.source.port, 8080) self.assertEqual(info.destination.host, b'127.0.0.1') self.assertEqual(info.destination.port, 8888)
Test that parsing happens when fed a complete line.
test_feedParsing
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
MIT
def test_feedParsingTooLong(self): """ Test that parsing fails if no newline is found in 108 bytes. """ parser = _v1parser.V1Parser() info, remaining = parser.feed(b'PROXY TCP4 127.0.0.1 127.0.0.1 ') self.assertFalse(info) self.assertFalse(remaining) info, remaining = parser.feed(b'8080 8888') self.assertFalse(info) self.assertFalse(remaining) self.assertRaises( InvalidProxyHeader, parser.feed, b' ' * 100, )
Test that parsing fails if no newline is found in 108 bytes.
test_feedParsingTooLong
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
MIT
def test_feedParsingOverflow(self): """ Test that parsing leaves overflow bytes in the buffer. """ parser = _v1parser.V1Parser() info, remaining = parser.feed( b'PROXY TCP4 127.0.0.1 127.0.0.1 8080 8888\r\nHTTP/1.1 GET /\r\n', ) self.assertTrue(info) self.assertEqual(remaining, b'HTTP/1.1 GET /\r\n') self.assertFalse(parser.buffer)
Test that parsing leaves overflow bytes in the buffer.
test_feedParsingOverflow
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v1parser.py
MIT
def _makeHeaderIPv4(sig=V2_SIGNATURE, verCom=b'\x21', famProto=b'\x11', addrLength=b'\x00\x0C', addrs=b'\x7F\x00\x00\x01\x7F\x00\x00\x01', ports=b'\x1F\x90\x22\xB8'): """ Construct a version 2 IPv4 header with custom bytes. @param sig: The protocol signature; defaults to valid L{V2_SIGNATURE}. @type sig: L{bytes} @param verCom: Protocol version and command. Defaults to V2 PROXY. @type verCom: L{bytes} @param famProto: Address family and protocol. Defaults to AF_INET/STREAM. @type famProto: L{bytes} @param addrLength: Network-endian byte length of payload. Defaults to description of default addrs/ports. @type addrLength: L{bytes} @param addrs: Address payload. Defaults to 127.0.0.1 for source and destination. @type addrs: L{bytes} @param ports: Source and destination ports. Defaults to 8080 for source 8888 for destination. @type ports: L{bytes} @return: A packet with header, addresses, and ports. @rtype: L{bytes} """ return sig + verCom + famProto + addrLength + addrs + ports
Construct a version 2 IPv4 header with custom bytes. @param sig: The protocol signature; defaults to valid L{V2_SIGNATURE}. @type sig: L{bytes} @param verCom: Protocol version and command. Defaults to V2 PROXY. @type verCom: L{bytes} @param famProto: Address family and protocol. Defaults to AF_INET/STREAM. @type famProto: L{bytes} @param addrLength: Network-endian byte length of payload. Defaults to description of default addrs/ports. @type addrLength: L{bytes} @param addrs: Address payload. Defaults to 127.0.0.1 for source and destination. @type addrs: L{bytes} @param ports: Source and destination ports. Defaults to 8080 for source 8888 for destination. @type ports: L{bytes} @return: A packet with header, addresses, and ports. @rtype: L{bytes}
_makeHeaderIPv4
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
MIT
def _makeHeaderUnix(sig=V2_SIGNATURE, verCom=b'\x21', famProto=b'\x31', addrLength=b'\x00\xD8', addrs=(b'\x2F\x68\x6F\x6D\x65\x2F\x74\x65\x73\x74\x73\x2F' b'\x6D\x79\x73\x6F\x63\x6B\x65\x74\x73\x2F\x73\x6F' b'\x63\x6B' + (b'\x00' * 82)) * 2): """ Construct a version 2 IPv4 header with custom bytes. @param sig: The protocol signature; defaults to valid L{V2_SIGNATURE}. @type sig: L{bytes} @param verCom: Protocol version and command. Defaults to V2 PROXY. @type verCom: L{bytes} @param famProto: Address family and protocol. Defaults to AF_UNIX/STREAM. @type famProto: L{bytes} @param addrLength: Network-endian byte length of payload. Defaults to 108 bytes for 2 null terminated paths. @type addrLength: L{bytes} @param addrs: Address payload. Defaults to C{/home/tests/mysockets/sock} for source and destination paths. @type addrs: L{bytes} @return: A packet with header, addresses, and8 ports. @rtype: L{bytes} """ return sig + verCom + famProto + addrLength + addrs
Construct a version 2 IPv4 header with custom bytes. @param sig: The protocol signature; defaults to valid L{V2_SIGNATURE}. @type sig: L{bytes} @param verCom: Protocol version and command. Defaults to V2 PROXY. @type verCom: L{bytes} @param famProto: Address family and protocol. Defaults to AF_UNIX/STREAM. @type famProto: L{bytes} @param addrLength: Network-endian byte length of payload. Defaults to 108 bytes for 2 null terminated paths. @type addrLength: L{bytes} @param addrs: Address payload. Defaults to C{/home/tests/mysockets/sock} for source and destination paths. @type addrs: L{bytes} @return: A packet with header, addresses, and8 ports. @rtype: L{bytes}
_makeHeaderUnix
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
MIT
def test_happyPathIPv4(self): """ Test if a well formed IPv4 header is parsed without error. """ header = _makeHeaderIPv4() self.assertTrue(_v2parser.V2Parser.parse(header))
Test if a well formed IPv4 header is parsed without error.
test_happyPathIPv4
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
MIT
def test_happyPathIPv6(self): """ Test if a well formed IPv6 header is parsed without error. """ header = _makeHeaderIPv6() self.assertTrue(_v2parser.V2Parser.parse(header))
Test if a well formed IPv6 header is parsed without error.
test_happyPathIPv6
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
MIT
def test_happyPathUnix(self): """ Test if a well formed UNIX header is parsed without error. """ header = _makeHeaderUnix() self.assertTrue(_v2parser.V2Parser.parse(header))
Test if a well formed UNIX header is parsed without error.
test_happyPathUnix
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
MIT
def test_invalidSignature(self): """ Test if an invalid signature block raises InvalidProxyError. """ header = _makeHeaderIPv4(sig=b'\x00'*12) self.assertRaises( InvalidProxyHeader, _v2parser.V2Parser.parse, header, )
Test if an invalid signature block raises InvalidProxyError.
test_invalidSignature
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
MIT
def test_invalidVersion(self): """ Test if an invalid version raises InvalidProxyError. """ header = _makeHeaderIPv4(verCom=b'\x11') self.assertRaises( InvalidProxyHeader, _v2parser.V2Parser.parse, header, )
Test if an invalid version raises InvalidProxyError.
test_invalidVersion
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
MIT
def test_invalidCommand(self): """ Test if an invalid command raises InvalidProxyError. """ header = _makeHeaderIPv4(verCom=b'\x23') self.assertRaises( InvalidProxyHeader, _v2parser.V2Parser.parse, header, )
Test if an invalid command raises InvalidProxyError.
test_invalidCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
MIT
def test_invalidFamily(self): """ Test if an invalid family raises InvalidProxyError. """ header = _makeHeaderIPv4(famProto=b'\x40') self.assertRaises( InvalidProxyHeader, _v2parser.V2Parser.parse, header, )
Test if an invalid family raises InvalidProxyError.
test_invalidFamily
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/haproxy/test/test_v2parser.py
MIT