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 ampBoxReceived(box): """ A box was received from the transport; dispatch it appropriately. """
A box was received from the transport; dispatch it appropriately.
ampBoxReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def stopReceivingBoxes(reason): """ No further boxes will be received on this connection. @type reason: L{Failure} """
No further boxes will be received on this connection. @type reason: L{Failure}
stopReceivingBoxes
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def locateResponder(name): """ Locate a responder method appropriate for the named command. @param name: the wire-level name (commandName) of the AMP command to be responded to. @type name: C{bytes} @return: a 1-argument callable that takes an L{AmpBox} with argument values for the given command, and returns an L{AmpBox} containing argument values for the named command, or a L{Deferred} that fires the same. """
Locate a responder method appropriate for the named command. @param name: the wire-level name (commandName) of the AMP command to be responded to. @type name: C{bytes} @return: a 1-argument callable that takes an L{AmpBox} with argument values for the given command, and returns an L{AmpBox} containing argument values for the named command, or a L{Deferred} that fires the same.
locateResponder
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def __init__(self, errorCode, description, fatal=False, local=None): """Create a remote error with an error code and description. @param errorCode: the AMP error code of this error. @type errorCode: C{bytes} @param description: some text to show to the user. @type description: C{str} @param fatal: a boolean, true if this error should terminate the connection. @param local: a local Failure, if one exists. """ if local: localwhat = ' (local)' othertb = local.getBriefTraceback() else: localwhat = '' othertb = '' # Backslash-escape errorCode. Python 3.5 can do this natively # ("backslashescape") but Python 2.7 and Python 3.4 can't. if _PY3: errorCodeForMessage = "".join( "\\x%2x" % (c,) if c >= 0x80 else chr(c) for c in errorCode) else: errorCodeForMessage = "".join( "\\x%2x" % (ord(c),) if ord(c) >= 0x80 else c for c in errorCode) if othertb: message = "Code<%s>%s: %s\n%s" % ( errorCodeForMessage, localwhat, description, othertb) else: message = "Code<%s>%s: %s" % ( errorCodeForMessage, localwhat, description) super(RemoteAmpError, self).__init__(message) self.local = local self.errorCode = errorCode self.description = description self.fatal = fatal
Create a remote error with an error code and description. @param errorCode: the AMP error code of this error. @type errorCode: C{bytes} @param description: some text to show to the user. @type description: C{str} @param fatal: a boolean, true if this error should terminate the connection. @param local: a local Failure, if one exists.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def __init__(self, *args, **kw): """ Initialize a new L{AmpBox}. In Python 3, keyword arguments MUST be Unicode/native strings whereas in Python 2 they could be either byte strings or Unicode strings. However, all keys of an L{AmpBox} MUST be byte strings, or possible to transparently coerce into byte strings (i.e. Python 2). In Python 3, therefore, native string keys are coerced to byte strings by encoding as ASCII. This can result in C{UnicodeEncodeError} being raised. @param args: See C{dict}, but all keys and values should be C{bytes}. On Python 3, native strings may be used as keys provided they contain only ASCII characters. @param kw: See C{dict}, but all keys and values should be C{bytes}. On Python 3, native strings may be used as keys provided they contain only ASCII characters. @raise UnicodeEncodeError: When a native string key cannot be coerced to an ASCII byte string (Python 3 only). """ super(AmpBox, self).__init__(*args, **kw) if _PY3: nonByteNames = [n for n in self if not isinstance(n, bytes)] for nonByteName in nonByteNames: byteName = nonByteName.encode("ascii") self[byteName] = self.pop(nonByteName)
Initialize a new L{AmpBox}. In Python 3, keyword arguments MUST be Unicode/native strings whereas in Python 2 they could be either byte strings or Unicode strings. However, all keys of an L{AmpBox} MUST be byte strings, or possible to transparently coerce into byte strings (i.e. Python 2). In Python 3, therefore, native string keys are coerced to byte strings by encoding as ASCII. This can result in C{UnicodeEncodeError} being raised. @param args: See C{dict}, but all keys and values should be C{bytes}. On Python 3, native strings may be used as keys provided they contain only ASCII characters. @param kw: See C{dict}, but all keys and values should be C{bytes}. On Python 3, native strings may be used as keys provided they contain only ASCII characters. @raise UnicodeEncodeError: When a native string key cannot be coerced to an ASCII byte string (Python 3 only).
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def copy(self): """ Return another AmpBox just like me. """ newBox = self.__class__() newBox.update(self) return newBox
Return another AmpBox just like me.
copy
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def serialize(self): """ Convert me into a wire-encoded string. @return: a C{bytes} encoded according to the rules described in the module docstring. """ i = sorted(iteritems(self)) L = [] w = L.append for k, v in i: if type(k) == unicode: raise TypeError("Unicode key not allowed: %r" % k) if type(v) == unicode: raise TypeError( "Unicode value for key %r not allowed: %r" % (k, v)) if len(k) > MAX_KEY_LENGTH: raise TooLong(True, True, k, None) if len(v) > MAX_VALUE_LENGTH: raise TooLong(False, True, v, k) for kv in k, v: w(pack("!H", len(kv))) w(kv) w(pack("!H", 0)) return b''.join(L)
Convert me into a wire-encoded string. @return: a C{bytes} encoded according to the rules described in the module docstring.
serialize
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _sendTo(self, proto): """ Serialize and send this box to an Amp instance. By the time it is being sent, several keys are required. I must have exactly ONE of:: _ask _answer _error If the '_ask' key is set, then the '_command' key must also be set. @param proto: an AMP instance. """ proto.sendBox(self)
Serialize and send this box to an Amp instance. By the time it is being sent, several keys are required. I must have exactly ONE of:: _ask _answer _error If the '_ask' key is set, then the '_command' key must also be set. @param proto: an AMP instance.
_sendTo
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _sendTo(self, proto): """ Immediately call loseConnection after sending. """ super(QuitBox, self)._sendTo(proto) proto.transport.loseConnection()
Immediately call loseConnection after sending.
_sendTo
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def __init__(self, innerProto, **kw): """ Create a _SwitchBox with the protocol to switch to after being sent. @param innerProto: the protocol instance to switch to. @type innerProto: an IProtocol provider. """ super(_SwitchBox, self).__init__(**kw) self.innerProto = innerProto
Create a _SwitchBox with the protocol to switch to after being sent. @param innerProto: the protocol instance to switch to. @type innerProto: an IProtocol provider.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _sendTo(self, proto): """ Send me; I am the last box on the connection. All further traffic will be over the new protocol. """ super(_SwitchBox, self)._sendTo(proto) proto._lockForSwitch() proto._switchTo(self.innerProto)
Send me; I am the last box on the connection. All further traffic will be over the new protocol.
_sendTo
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def startReceivingBoxes(self, boxSender): """ The given boxSender is going to start calling boxReceived on this L{BoxDispatcher}. @param boxSender: The L{IBoxSender} to send command responses to. """ self.boxSender = boxSender
The given boxSender is going to start calling boxReceived on this L{BoxDispatcher}. @param boxSender: The L{IBoxSender} to send command responses to.
startReceivingBoxes
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def stopReceivingBoxes(self, reason): """ No further boxes will be received here. Terminate all currently outstanding command deferreds with the given reason. """ self.failAllOutgoing(reason)
No further boxes will be received here. Terminate all currently outstanding command deferreds with the given reason.
stopReceivingBoxes
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def failAllOutgoing(self, reason): """ Call the errback on all outstanding requests awaiting responses. @param reason: the Failure instance to pass to those errbacks. """ self._failAllReason = reason OR = self._outstandingRequests.items() self._outstandingRequests = None # we can never send another request for key, value in OR: value.errback(reason)
Call the errback on all outstanding requests awaiting responses. @param reason: the Failure instance to pass to those errbacks.
failAllOutgoing
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _nextTag(self): """ Generate protocol-local serial numbers for _ask keys. @return: a string that has not yet been used on this connection. """ self._counter += 1 return (b'%x' % (self._counter,))
Generate protocol-local serial numbers for _ask keys. @return: a string that has not yet been used on this connection.
_nextTag
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _sendBoxCommand(self, command, box, requiresAnswer=True): """ Send a command across the wire with the given C{amp.Box}. Mutate the given box to give it any additional keys (_command, _ask) required for the command and request/response machinery, then send it. If requiresAnswer is True, returns a C{Deferred} which fires when a response is received. The C{Deferred} is fired with an C{amp.Box} on success, or with an C{amp.RemoteAmpError} if an error is received. If the Deferred fails and the error is not handled by the caller of this method, the failure will be logged and the connection dropped. @param command: a C{bytes}, the name of the command to issue. @param box: an AmpBox with the arguments for the command. @param requiresAnswer: a boolean. Defaults to True. If True, return a Deferred which will fire when the other side responds to this command. If False, return None and do not ask the other side for acknowledgement. @return: a Deferred which fires the AmpBox that holds the response to this command, or None, as specified by requiresAnswer. @raise ProtocolSwitched: if the protocol has been switched. """ if self._failAllReason is not None: return fail(self._failAllReason) box[COMMAND] = command tag = self._nextTag() if requiresAnswer: box[ASK] = tag box._sendTo(self.boxSender) if requiresAnswer: result = self._outstandingRequests[tag] = Deferred() else: result = None return result
Send a command across the wire with the given C{amp.Box}. Mutate the given box to give it any additional keys (_command, _ask) required for the command and request/response machinery, then send it. If requiresAnswer is True, returns a C{Deferred} which fires when a response is received. The C{Deferred} is fired with an C{amp.Box} on success, or with an C{amp.RemoteAmpError} if an error is received. If the Deferred fails and the error is not handled by the caller of this method, the failure will be logged and the connection dropped. @param command: a C{bytes}, the name of the command to issue. @param box: an AmpBox with the arguments for the command. @param requiresAnswer: a boolean. Defaults to True. If True, return a Deferred which will fire when the other side responds to this command. If False, return None and do not ask the other side for acknowledgement. @return: a Deferred which fires the AmpBox that holds the response to this command, or None, as specified by requiresAnswer. @raise ProtocolSwitched: if the protocol has been switched.
_sendBoxCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def callRemoteString(self, command, requiresAnswer=True, **kw): """ This is a low-level API, designed only for optimizing simple messages for which the overhead of parsing is too great. @param command: a C{bytes} naming the command. @param kw: arguments to the amp box. @param requiresAnswer: a boolean. Defaults to True. If True, return a Deferred which will fire when the other side responds to this command. If False, return None and do not ask the other side for acknowledgement. @return: a Deferred which fires the AmpBox that holds the response to this command, or None, as specified by requiresAnswer. """ box = Box(kw) return self._sendBoxCommand(command, box, requiresAnswer)
This is a low-level API, designed only for optimizing simple messages for which the overhead of parsing is too great. @param command: a C{bytes} naming the command. @param kw: arguments to the amp box. @param requiresAnswer: a boolean. Defaults to True. If True, return a Deferred which will fire when the other side responds to this command. If False, return None and do not ask the other side for acknowledgement. @return: a Deferred which fires the AmpBox that holds the response to this command, or None, as specified by requiresAnswer.
callRemoteString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def callRemote(self, commandType, *a, **kw): """ This is the primary high-level API for sending messages via AMP. Invoke it with a command and appropriate arguments to send a message to this connection's peer. @param commandType: a subclass of Command. @type commandType: L{type} @param a: Positional (special) parameters taken by the command. Positional parameters will typically not be sent over the wire. The only command included with AMP which uses positional parameters is L{ProtocolSwitchCommand}, which takes the protocol that will be switched to as its first argument. @param kw: Keyword arguments taken by the command. These are the arguments declared in the command's 'arguments' attribute. They will be encoded and sent to the peer as arguments for the L{commandType}. @return: If L{commandType} has a C{requiresAnswer} attribute set to L{False}, then return L{None}. Otherwise, return a L{Deferred} which fires with a dictionary of objects representing the result of this call. Additionally, this L{Deferred} may fail with an exception representing a connection failure, with L{UnknownRemoteError} if the other end of the connection fails for an unknown reason, or with any error specified as a key in L{commandType}'s C{errors} dictionary. """ # XXX this takes command subclasses and not command objects on purpose. # There's really no reason to have all this back-and-forth between # command objects and the protocol, and the extra object being created # (the Command instance) is pointless. Command is kind of like # Interface, and should be more like it. # In other words, the fact that commandType is instantiated here is an # implementation detail. Don't rely on it. try: co = commandType(*a, **kw) except: return fail() return co._doCommand(self)
This is the primary high-level API for sending messages via AMP. Invoke it with a command and appropriate arguments to send a message to this connection's peer. @param commandType: a subclass of Command. @type commandType: L{type} @param a: Positional (special) parameters taken by the command. Positional parameters will typically not be sent over the wire. The only command included with AMP which uses positional parameters is L{ProtocolSwitchCommand}, which takes the protocol that will be switched to as its first argument. @param kw: Keyword arguments taken by the command. These are the arguments declared in the command's 'arguments' attribute. They will be encoded and sent to the peer as arguments for the L{commandType}. @return: If L{commandType} has a C{requiresAnswer} attribute set to L{False}, then return L{None}. Otherwise, return a L{Deferred} which fires with a dictionary of objects representing the result of this call. Additionally, this L{Deferred} may fail with an exception representing a connection failure, with L{UnknownRemoteError} if the other end of the connection fails for an unknown reason, or with any error specified as a key in L{commandType}'s C{errors} dictionary.
callRemote
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def unhandledError(self, failure): """ This is a terminal callback called after application code has had a chance to quash any errors. """ return self.boxSender.unhandledError(failure)
This is a terminal callback called after application code has had a chance to quash any errors.
unhandledError
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _answerReceived(self, box): """ An AMP box was received that answered a command previously sent with L{callRemote}. @param box: an AmpBox with a value for its L{ANSWER} key. """ question = self._outstandingRequests.pop(box[ANSWER]) question.addErrback(self.unhandledError) question.callback(box)
An AMP box was received that answered a command previously sent with L{callRemote}. @param box: an AmpBox with a value for its L{ANSWER} key.
_answerReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _errorReceived(self, box): """ An AMP box was received that answered a command previously sent with L{callRemote}, with an error. @param box: an L{AmpBox} with a value for its L{ERROR}, L{ERROR_CODE}, and L{ERROR_DESCRIPTION} keys. """ question = self._outstandingRequests.pop(box[ERROR]) question.addErrback(self.unhandledError) errorCode = box[ERROR_CODE] description = box[ERROR_DESCRIPTION] if isinstance(description, bytes): description = description.decode("utf-8", "replace") if errorCode in PROTOCOL_ERRORS: exc = PROTOCOL_ERRORS[errorCode](errorCode, description) else: exc = RemoteAmpError(errorCode, description) question.errback(Failure(exc))
An AMP box was received that answered a command previously sent with L{callRemote}, with an error. @param box: an L{AmpBox} with a value for its L{ERROR}, L{ERROR_CODE}, and L{ERROR_DESCRIPTION} keys.
_errorReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _commandReceived(self, box): """ @param box: an L{AmpBox} with a value for its L{COMMAND} and L{ASK} keys. """ def formatAnswer(answerBox): answerBox[ANSWER] = box[ASK] return answerBox def formatError(error): if error.check(RemoteAmpError): code = error.value.errorCode desc = error.value.description if isinstance(desc, unicode): desc = desc.encode("utf-8", "replace") if error.value.fatal: errorBox = QuitBox() else: errorBox = AmpBox() else: errorBox = QuitBox() log.err(error) # here is where server-side logging happens # if the error isn't handled code = UNKNOWN_ERROR_CODE desc = b"Unknown Error" errorBox[ERROR] = box[ASK] errorBox[ERROR_DESCRIPTION] = desc errorBox[ERROR_CODE] = code return errorBox deferred = self.dispatchCommand(box) if ASK in box: deferred.addCallbacks(formatAnswer, formatError) deferred.addCallback(self._safeEmit) deferred.addErrback(self.unhandledError)
@param box: an L{AmpBox} with a value for its L{COMMAND} and L{ASK} keys.
_commandReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def ampBoxReceived(self, box): """ An AmpBox was received, representing a command, or an answer to a previously issued command (either successful or erroneous). Respond to it according to its contents. @param box: an AmpBox @raise NoEmptyBoxes: when a box is received that does not contain an '_answer', '_command' / '_ask', or '_error' key; i.e. one which does not fit into the command / response protocol defined by AMP. """ if ANSWER in box: self._answerReceived(box) elif ERROR in box: self._errorReceived(box) elif COMMAND in box: self._commandReceived(box) else: raise NoEmptyBoxes(box)
An AmpBox was received, representing a command, or an answer to a previously issued command (either successful or erroneous). Respond to it according to its contents. @param box: an AmpBox @raise NoEmptyBoxes: when a box is received that does not contain an '_answer', '_command' / '_ask', or '_error' key; i.e. one which does not fit into the command / response protocol defined by AMP.
ampBoxReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _safeEmit(self, aBox): """ Emit a box, ignoring L{ProtocolSwitched} and L{ConnectionLost} errors which cannot be usefully handled. """ try: aBox._sendTo(self.boxSender) except (ProtocolSwitched, ConnectionLost): pass
Emit a box, ignoring L{ProtocolSwitched} and L{ConnectionLost} errors which cannot be usefully handled.
_safeEmit
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def dispatchCommand(self, box): """ A box with a _command key was received. Dispatch it to a local handler call it. @param proto: an AMP instance. @param box: an AmpBox to be dispatched. """ cmd = box[COMMAND] responder = self.locator.locateResponder(cmd) if responder is None: description = "Unhandled Command: %r" % (cmd,) return fail(RemoteAmpError( UNHANDLED_ERROR_CODE, description, False, local=Failure(UnhandledCommand()))) return maybeDeferred(responder, box)
A box with a _command key was received. Dispatch it to a local handler call it. @param proto: an AMP instance. @param box: an AmpBox to be dispatched.
dispatchCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _wrapWithSerialization(self, aCallable, command): """ Wrap aCallable with its command's argument de-serialization and result serialization logic. @param aCallable: a callable with a 'command' attribute, designed to be called with keyword arguments. @param command: the command class whose serialization to use. @return: a 1-arg callable which, when invoked with an AmpBox, will deserialize the argument list and invoke appropriate user code for the callable's command, returning a Deferred which fires with the result or fails with an error. """ def doit(box): kw = command.parseArguments(box, self) def checkKnownErrors(error): key = error.trap(*command.allErrors) code = command.allErrors[key] desc = str(error.value) return Failure(RemoteAmpError( code, desc, key in command.fatalErrors, local=error)) def makeResponseFor(objects): try: return command.makeResponse(objects, self) except: # let's helpfully log this. originalFailure = Failure() raise BadLocalReturn( "%r returned %r and %r could not serialize it" % ( aCallable, objects, command), originalFailure) return maybeDeferred(aCallable, **kw).addCallback( makeResponseFor).addErrback( checkKnownErrors) return doit
Wrap aCallable with its command's argument de-serialization and result serialization logic. @param aCallable: a callable with a 'command' attribute, designed to be called with keyword arguments. @param command: the command class whose serialization to use. @return: a 1-arg callable which, when invoked with an AmpBox, will deserialize the argument list and invoke appropriate user code for the callable's command, returning a Deferred which fires with the result or fails with an error.
_wrapWithSerialization
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def lookupFunction(self, name): """ Deprecated synonym for L{CommandLocator.locateResponder} """ if self.__class__.lookupFunction != CommandLocator.lookupFunction: return CommandLocator.locateResponder(self, name) else: warnings.warn("Call locateResponder, not lookupFunction.", category=PendingDeprecationWarning, stacklevel=2) return self.locateResponder(name)
Deprecated synonym for L{CommandLocator.locateResponder}
lookupFunction
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def locateResponder(self, name): """ Locate a callable to invoke when executing the named command. @param name: the normalized name (from the wire) of the command. @type name: C{bytes} @return: a 1-argument function that takes a Box and returns a box or a Deferred which fires a Box, for handling the command identified by the given name, or None, if no appropriate responder can be found. """ # Try to find a high-level method to invoke, and if we can't find one, # fall back to a low-level one. cd = self._commandDispatch if name in cd: commandClass, responderFunc = cd[name] if _PY3: responderMethod = types.MethodType( responderFunc, self) else: responderMethod = types.MethodType( responderFunc, self, self.__class__) return self._wrapWithSerialization(responderMethod, commandClass)
Locate a callable to invoke when executing the named command. @param name: the normalized name (from the wire) of the command. @type name: C{bytes} @return: a 1-argument function that takes a Box and returns a box or a Deferred which fires a Box, for handling the command identified by the given name, or None, if no appropriate responder can be found.
locateResponder
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def locateResponder(self, name): """ Locate a callable to invoke when executing the named command. @return: a function with the name C{"amp_" + name} on the same instance, or None if no such function exists. This function will then be called with the L{AmpBox} itself as an argument. @param name: the normalized name (from the wire) of the command. @type name: C{bytes} """ fName = nativeString(self.baseDispatchPrefix + name.upper()) return getattr(self, fName, None)
Locate a callable to invoke when executing the named command. @return: a function with the name C{"amp_" + name} on the same instance, or None if no such function exists. This function will then be called with the L{AmpBox} itself as an argument. @param name: the normalized name (from the wire) of the command. @type name: C{bytes}
locateResponder
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _wireNameToPythonIdentifier(key): """ (Private) Normalize an argument name from the wire for use with Python code. If the return value is going to be a python keyword it will be capitalized. If it contains any dashes they will be replaced with underscores. The rationale behind this method is that AMP should be an inherently multi-language protocol, so message keys may contain all manner of bizarre bytes. This is not a complete solution; there are still forms of arguments that this implementation will be unable to parse. However, Python identifiers share a huge raft of properties with identifiers from many other languages, so this is a 'good enough' effort for now. We deal explicitly with dashes because that is the most likely departure: Lisps commonly use dashes to separate method names, so protocols initially implemented in a lisp amp dialect may use dashes in argument or command names. @param key: a C{bytes}, looking something like 'foo-bar-baz' or 'from' @type key: C{bytes} @return: a native string which is a valid python identifier, looking something like 'foo_bar_baz' or 'From'. """ lkey = nativeString(key.replace(b"-", b"_")) if lkey in PYTHON_KEYWORDS: return lkey.title() return lkey
(Private) Normalize an argument name from the wire for use with Python code. If the return value is going to be a python keyword it will be capitalized. If it contains any dashes they will be replaced with underscores. The rationale behind this method is that AMP should be an inherently multi-language protocol, so message keys may contain all manner of bizarre bytes. This is not a complete solution; there are still forms of arguments that this implementation will be unable to parse. However, Python identifiers share a huge raft of properties with identifiers from many other languages, so this is a 'good enough' effort for now. We deal explicitly with dashes because that is the most likely departure: Lisps commonly use dashes to separate method names, so protocols initially implemented in a lisp amp dialect may use dashes in argument or command names. @param key: a C{bytes}, looking something like 'foo-bar-baz' or 'from' @type key: C{bytes} @return: a native string which is a valid python identifier, looking something like 'foo_bar_baz' or 'From'.
_wireNameToPythonIdentifier
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def __init__(self, optional=False): """ Create an Argument. @param optional: a boolean indicating whether this argument can be omitted in the protocol. """ self.optional = optional
Create an Argument. @param optional: a boolean indicating whether this argument can be omitted in the protocol.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def retrieve(self, d, name, proto): """ Retrieve the given key from the given dictionary, removing it if found. @param d: a dictionary. @param name: a key in I{d}. @param proto: an instance of an AMP. @raise KeyError: if I am not optional and no value was found. @return: d[name]. """ if self.optional: value = d.get(name) if value is not None: del d[name] else: value = d.pop(name) return value
Retrieve the given key from the given dictionary, removing it if found. @param d: a dictionary. @param name: a key in I{d}. @param proto: an instance of an AMP. @raise KeyError: if I am not optional and no value was found. @return: d[name].
retrieve
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def fromBox(self, name, strings, objects, proto): """ Populate an 'out' dictionary with mapping names to Python values decoded from an 'in' AmpBox mapping strings to string values. @param name: the argument name to retrieve @type name: C{bytes} @param strings: The AmpBox to read string(s) from, a mapping of argument names to string values. @type strings: AmpBox @param objects: The dictionary to write object(s) to, a mapping of names to Python objects. Keys will be native strings. @type objects: dict @param proto: an AMP instance. """ st = self.retrieve(strings, name, proto) nk = _wireNameToPythonIdentifier(name) if self.optional and st is None: objects[nk] = None else: objects[nk] = self.fromStringProto(st, proto)
Populate an 'out' dictionary with mapping names to Python values decoded from an 'in' AmpBox mapping strings to string values. @param name: the argument name to retrieve @type name: C{bytes} @param strings: The AmpBox to read string(s) from, a mapping of argument names to string values. @type strings: AmpBox @param objects: The dictionary to write object(s) to, a mapping of names to Python objects. Keys will be native strings. @type objects: dict @param proto: an AMP instance.
fromBox
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def toBox(self, name, strings, objects, proto): """ Populate an 'out' AmpBox with strings encoded from an 'in' dictionary mapping names to Python values. @param name: the argument name to retrieve @type name: C{bytes} @param strings: The AmpBox to write string(s) to, a mapping of argument names to string values. @type strings: AmpBox @param objects: The dictionary to read object(s) from, a mapping of names to Python objects. Keys should be native strings. @type objects: dict @param proto: the protocol we are converting for. @type proto: AMP """ obj = self.retrieve(objects, _wireNameToPythonIdentifier(name), proto) if self.optional and obj is None: # strings[name] = None pass else: strings[name] = self.toStringProto(obj, proto)
Populate an 'out' AmpBox with strings encoded from an 'in' dictionary mapping names to Python values. @param name: the argument name to retrieve @type name: C{bytes} @param strings: The AmpBox to write string(s) to, a mapping of argument names to string values. @type strings: AmpBox @param objects: The dictionary to read object(s) from, a mapping of names to Python objects. Keys should be native strings. @type objects: dict @param proto: the protocol we are converting for. @type proto: AMP
toBox
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def fromStringProto(self, inString, proto): """ Convert a string to a Python value. @param inString: the string to convert. @type inString: C{bytes} @param proto: the protocol we are converting for. @type proto: AMP @return: a Python object. """ return self.fromString(inString)
Convert a string to a Python value. @param inString: the string to convert. @type inString: C{bytes} @param proto: the protocol we are converting for. @type proto: AMP @return: a Python object.
fromStringProto
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def toStringProto(self, inObject, proto): """ Convert a Python object to a string. @param inObject: the object to convert. @param proto: the protocol we are converting for. @type proto: AMP """ return self.toString(inObject)
Convert a Python object to a string. @param inObject: the object to convert. @param proto: the protocol we are converting for. @type proto: AMP
toStringProto
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def fromString(self, inString): """ Convert a string to a Python object. Subclasses must implement this. @param inString: the string to convert. @type inString: C{bytes} @return: the decoded value from C{inString} """
Convert a string to a Python object. Subclasses must implement this. @param inString: the string to convert. @type inString: C{bytes} @return: the decoded value from C{inString}
fromString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def toString(self, inObject): """ Convert a Python object into a string for passing over the network. @param inObject: an object of the type that this Argument is intended to deal with. @return: the wire encoding of inObject @rtype: C{bytes} """
Convert a Python object into a string for passing over the network. @param inObject: an object of the type that this Argument is intended to deal with. @return: the wire encoding of inObject @rtype: C{bytes}
toString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def fromString(self, inString): """ Convert the serialized form of a list of instances of some type back into that list. """ strings = [] parser = Int16StringReceiver() parser.stringReceived = strings.append parser.dataReceived(inString) elementFromString = self.elementType.fromString return [elementFromString(string) for string in strings]
Convert the serialized form of a list of instances of some type back into that list.
fromString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def toString(self, inObject): """ Serialize the given list of objects to a single string. """ strings = [] for obj in inObject: serialized = self.elementType.toString(obj) strings.append(pack('!H', len(serialized))) strings.append(serialized) return b''.join(strings)
Serialize the given list of objects to a single string.
toString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def __init__(self, subargs, optional=False): """ Create an AmpList. @param subargs: a list of 2-tuples of ('name', argument) describing the schema of the dictionaries in the sequence of amp boxes. @type subargs: A C{list} of (C{bytes}, L{Argument}) tuples. @param optional: a boolean indicating whether this argument can be omitted in the protocol. """ assert all(isinstance(name, bytes) for name, _ in subargs), ( "AmpList should be defined with a list of (name, argument) " "tuples where `name' is a byte string, got: %r" % (subargs, )) self.subargs = subargs Argument.__init__(self, optional)
Create an AmpList. @param subargs: a list of 2-tuples of ('name', argument) describing the schema of the dictionaries in the sequence of amp boxes. @type subargs: A C{list} of (C{bytes}, L{Argument}) tuples. @param optional: a boolean indicating whether this argument can be omitted in the protocol.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def fromStringProto(self, inString, proto): """ Take a unique identifier associated with a file descriptor which must have been received by now and use it to look up that descriptor in a dictionary where they are kept. @param inString: The base representation (as a byte string) of an ordinal indicating which file descriptor corresponds to this usage of this argument. @type inString: C{str} @param proto: The protocol used to receive this descriptor. This protocol must be connected via a transport providing L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}. @type proto: L{BinaryBoxProtocol} @return: The file descriptor represented by C{inString}. @rtype: C{int} """ return proto._getDescriptor(int(inString))
Take a unique identifier associated with a file descriptor which must have been received by now and use it to look up that descriptor in a dictionary where they are kept. @param inString: The base representation (as a byte string) of an ordinal indicating which file descriptor corresponds to this usage of this argument. @type inString: C{str} @param proto: The protocol used to receive this descriptor. This protocol must be connected via a transport providing L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}. @type proto: L{BinaryBoxProtocol} @return: The file descriptor represented by C{inString}. @rtype: C{int}
fromStringProto
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def toStringProto(self, inObject, proto): """ Send C{inObject}, an integer file descriptor, over C{proto}'s connection and return a unique identifier which will allow the receiver to associate the file descriptor with this argument. @param inObject: A file descriptor to duplicate over an AMP connection as the value for this argument. @type inObject: C{int} @param proto: The protocol which will be used to send this descriptor. This protocol must be connected via a transport providing L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}. @return: A byte string which can be used by the receiver to reconstruct the file descriptor. @type: C{str} """ identifier = proto._sendFileDescriptor(inObject) outString = Integer.toStringProto(self, identifier, proto) return outString
Send C{inObject}, an integer file descriptor, over C{proto}'s connection and return a unique identifier which will allow the receiver to associate the file descriptor with this argument. @param inObject: A file descriptor to duplicate over an AMP connection as the value for this argument. @type inObject: C{int} @param proto: The protocol which will be used to send this descriptor. This protocol must be connected via a transport providing L{IUNIXTransport<twisted.internet.interfaces.IUNIXTransport>}. @return: A byte string which can be used by the receiver to reconstruct the file descriptor. @type: C{str}
toStringProto
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def __init__(self, **kw): """ Create an instance of this command with specified values for its parameters. In Python 3, keyword arguments MUST be Unicode/native strings whereas in Python 2 they could be either byte strings or Unicode strings. A L{Command}'s arguments are defined in its schema using C{bytes} names. The values for those arguments are plucked from the keyword arguments using the name returned from L{_wireNameToPythonIdentifier}. In other words, keyword arguments should be named using the Python-side equivalent of the on-wire (C{bytes}) name. @param kw: a dict containing an appropriate value for each name specified in the L{arguments} attribute of my class. @raise InvalidSignature: if you forgot any required arguments. """ self.structured = kw forgotten = [] for name, arg in self.arguments: pythonName = _wireNameToPythonIdentifier(name) if pythonName not in self.structured and not arg.optional: forgotten.append(pythonName) if forgotten: raise InvalidSignature("forgot %s for %s" % ( ', '.join(forgotten), self.commandName)) forgotten = []
Create an instance of this command with specified values for its parameters. In Python 3, keyword arguments MUST be Unicode/native strings whereas in Python 2 they could be either byte strings or Unicode strings. A L{Command}'s arguments are defined in its schema using C{bytes} names. The values for those arguments are plucked from the keyword arguments using the name returned from L{_wireNameToPythonIdentifier}. In other words, keyword arguments should be named using the Python-side equivalent of the on-wire (C{bytes}) name. @param kw: a dict containing an appropriate value for each name specified in the L{arguments} attribute of my class. @raise InvalidSignature: if you forgot any required arguments.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def makeResponse(cls, objects, proto): """ Serialize a mapping of arguments using this L{Command}'s response schema. @param objects: a dict with keys matching the names specified in self.response, having values of the types that the Argument objects in self.response can format. @param proto: an L{AMP}. @return: an L{AmpBox}. """ try: responseType = cls.responseType() except: return fail() return _objectsToStrings(objects, cls.response, responseType, proto)
Serialize a mapping of arguments using this L{Command}'s response schema. @param objects: a dict with keys matching the names specified in self.response, having values of the types that the Argument objects in self.response can format. @param proto: an L{AMP}. @return: an L{AmpBox}.
makeResponse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def makeArguments(cls, objects, proto): """ Serialize a mapping of arguments using this L{Command}'s argument schema. @param objects: a dict with keys similar to the names specified in self.arguments, having values of the types that the Argument objects in self.arguments can parse. @param proto: an L{AMP}. @return: An instance of this L{Command}'s C{commandType}. """ allowedNames = set() for (argName, ignored) in cls.arguments: allowedNames.add(_wireNameToPythonIdentifier(argName)) for intendedArg in objects: if intendedArg not in allowedNames: raise InvalidSignature( "%s is not a valid argument" % (intendedArg,)) return _objectsToStrings(objects, cls.arguments, cls.commandType(), proto)
Serialize a mapping of arguments using this L{Command}'s argument schema. @param objects: a dict with keys similar to the names specified in self.arguments, having values of the types that the Argument objects in self.arguments can parse. @param proto: an L{AMP}. @return: An instance of this L{Command}'s C{commandType}.
makeArguments
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def parseResponse(cls, box, protocol): """ Parse a mapping of serialized arguments using this L{Command}'s response schema. @param box: A mapping of response-argument names to the serialized forms of those arguments. @param protocol: The L{AMP} protocol. @return: A mapping of response-argument names to the parsed forms. """ return _stringsToObjects(box, cls.response, protocol)
Parse a mapping of serialized arguments using this L{Command}'s response schema. @param box: A mapping of response-argument names to the serialized forms of those arguments. @param protocol: The L{AMP} protocol. @return: A mapping of response-argument names to the parsed forms.
parseResponse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def parseArguments(cls, box, protocol): """ Parse a mapping of serialized arguments using this L{Command}'s argument schema. @param box: A mapping of argument names to the seralized forms of those arguments. @param protocol: The L{AMP} protocol. @return: A mapping of argument names to the parsed forms. """ return _stringsToObjects(box, cls.arguments, protocol)
Parse a mapping of serialized arguments using this L{Command}'s argument schema. @param box: A mapping of argument names to the seralized forms of those arguments. @param protocol: The L{AMP} protocol. @return: A mapping of argument names to the parsed forms.
parseArguments
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def responder(cls, methodfunc): """ Declare a method to be a responder for a particular command. This is a decorator. Use like so:: class MyCommand(Command): arguments = [('a', ...), ('b', ...)] class MyProto(AMP): def myFunMethod(self, a, b): ... MyCommand.responder(myFunMethod) Notes: Although decorator syntax is not used within Twisted, this function returns its argument and is therefore safe to use with decorator syntax. This is not thread safe. Don't declare AMP subclasses in other threads. Don't declare responders outside the scope of AMP subclasses; the behavior is undefined. @param methodfunc: A function which will later become a method, which has a keyword signature compatible with this command's L{argument} list and returns a dictionary with a set of keys compatible with this command's L{response} list. @return: the methodfunc parameter. """ CommandLocator._currentClassCommands.append((cls, methodfunc)) return methodfunc
Declare a method to be a responder for a particular command. This is a decorator. Use like so:: class MyCommand(Command): arguments = [('a', ...), ('b', ...)] class MyProto(AMP): def myFunMethod(self, a, b): ... MyCommand.responder(myFunMethod) Notes: Although decorator syntax is not used within Twisted, this function returns its argument and is therefore safe to use with decorator syntax. This is not thread safe. Don't declare AMP subclasses in other threads. Don't declare responders outside the scope of AMP subclasses; the behavior is undefined. @param methodfunc: A function which will later become a method, which has a keyword signature compatible with this command's L{argument} list and returns a dictionary with a set of keys compatible with this command's L{response} list. @return: the methodfunc parameter.
responder
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _doCommand(self, proto): """ Encode and send this Command to the given protocol. @param proto: an AMP, representing the connection to send to. @return: a Deferred which will fire or error appropriately when the other side responds to the command (or error if the connection is lost before it is responded to). """ def _massageError(error): error.trap(RemoteAmpError) rje = error.value errorType = self.reverseErrors.get(rje.errorCode, UnknownRemoteError) return Failure(errorType(rje.description)) d = proto._sendBoxCommand(self.commandName, self.makeArguments(self.structured, proto), self.requiresAnswer) if self.requiresAnswer: d.addCallback(self.parseResponse, proto) d.addErrback(_massageError) return d
Encode and send this Command to the given protocol. @param proto: an AMP, representing the connection to send to. @return: a Deferred which will fire or error appropriately when the other side responds to the command (or error if the connection is lost before it is responded to).
_doCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def __init__(self, client): """ Create a _NoCertificate which either is or isn't for the client side of the connection. @param client: True if we are a client and should truly have no certificate and be anonymous, False if we are a server and actually have to generate a temporary certificate. @type client: bool """ self.client = client
Create a _NoCertificate which either is or isn't for the client side of the connection. @param client: True if we are a client and should truly have no certificate and be anonymous, False if we are a server and actually have to generate a temporary certificate. @type client: bool
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def options(self, *authorities): """ Behaves like L{twisted.internet.ssl.PrivateCertificate.options}(). """ if not self.client: # do some crud with sslverify to generate a temporary self-signed # certificate. This is SLOOOWWWWW so it is only in the absolute # worst, most naive case. # We have to do this because OpenSSL will not let both the server # and client be anonymous. sharedDN = DN(CN='TEMPORARY CERTIFICATE') key = KeyPair.generate() cr = key.certificateRequest(sharedDN) sscrd = key.signCertificateRequest(sharedDN, cr, lambda dn: True, 1) cert = key.newCertificate(sscrd) return cert.options(*authorities) options = dict() if authorities: options.update(dict(verify=True, requireCertificate=True, caCerts=[auth.original for auth in authorities])) occo = CertificateOptions(**options) return occo
Behaves like L{twisted.internet.ssl.PrivateCertificate.options}().
options
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _sendTo(self, proto): """ Send my encoded value to the protocol, then initiate TLS. """ ab = AmpBox(self) for k in [b'tls_localCertificate', b'tls_verifyAuthorities']: ab.pop(k, None) ab._sendTo(proto) proto._startTLS(self.certificate, self.verify)
Send my encoded value to the protocol, then initiate TLS.
_sendTo
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def __init__(self, **kw): """ Create a StartTLS command. (This is private. Use AMP.callRemote.) @param tls_localCertificate: the PrivateCertificate object to use to secure the connection. If it's None, or unspecified, an ephemeral DH key is used instead. @param tls_verifyAuthorities: a list of Certificate objects which represent root certificates to verify our peer with. """ if ssl is None: raise RuntimeError("TLS not available.") self.certificate = kw.pop('tls_localCertificate', _NoCertificate(True)) self.authorities = kw.pop('tls_verifyAuthorities', None) Command.__init__(self, **kw)
Create a StartTLS command. (This is private. Use AMP.callRemote.) @param tls_localCertificate: the PrivateCertificate object to use to secure the connection. If it's None, or unspecified, an ephemeral DH key is used instead. @param tls_verifyAuthorities: a list of Certificate objects which represent root certificates to verify our peer with.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _doCommand(self, proto): """ When a StartTLS command is sent, prepare to start TLS, but don't actually do it; wait for the acknowledgement, then initiate the TLS handshake. """ d = Command._doCommand(self, proto) proto._prepareTLS(self.certificate, self.authorities) # XXX before we get back to user code we are going to start TLS... def actuallystart(response): proto._startTLS(self.certificate, self.authorities) return response d.addCallback(actuallystart) return d
When a StartTLS command is sent, prepare to start TLS, but don't actually do it; wait for the acknowledgement, then initiate the TLS handshake.
_doCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def __init__(self, _protoToSwitchToFactory, **kw): """ Create a ProtocolSwitchCommand. @param _protoToSwitchToFactory: a ProtocolFactory which will generate the Protocol to switch to. @param kw: Keyword arguments, encoded and handled normally as L{Command} would. """ self.protoToSwitchToFactory = _protoToSwitchToFactory super(ProtocolSwitchCommand, self).__init__(**kw)
Create a ProtocolSwitchCommand. @param _protoToSwitchToFactory: a ProtocolFactory which will generate the Protocol to switch to. @param kw: Keyword arguments, encoded and handled normally as L{Command} would.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _doCommand(self, proto): """ When we emit a ProtocolSwitchCommand, lock the protocol, but don't actually switch to the new protocol unless an acknowledgement is received. If an error is received, switch back. """ d = super(ProtocolSwitchCommand, self)._doCommand(proto) proto._lockForSwitch() def switchNow(ign): innerProto = self.protoToSwitchToFactory.buildProtocol( proto.transport.getPeer()) proto._switchTo(innerProto, self.protoToSwitchToFactory) return ign def handle(ign): proto._unlockFromSwitch() self.protoToSwitchToFactory.clientConnectionFailed( None, Failure(CONNECTION_LOST)) return ign return d.addCallbacks(switchNow, handle)
When we emit a ProtocolSwitchCommand, lock the protocol, but don't actually switch to the new protocol unless an acknowledgement is received. If an error is received, switch back.
_doCommand
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _sendFileDescriptor(self, descriptor): """ Assign and return the next ordinal to the given descriptor after sending the descriptor over this protocol's transport. """ self.transport.sendFileDescriptor(descriptor) return self._sendingDescriptorCounter()
Assign and return the next ordinal to the given descriptor after sending the descriptor over this protocol's transport.
_sendFileDescriptor
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def fileDescriptorReceived(self, descriptor): """ Collect received file descriptors to be claimed later by L{Descriptor}. @param descriptor: The received file descriptor. @type descriptor: C{int} """ self._descriptors[self._receivingDescriptorCounter()] = descriptor
Collect received file descriptors to be claimed later by L{Descriptor}. @param descriptor: The received file descriptor. @type descriptor: C{int}
fileDescriptorReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _switchTo(self, newProto, clientFactory=None): """ Switch this BinaryBoxProtocol's transport to a new protocol. You need to do this 'simultaneously' on both ends of a connection; the easiest way to do this is to use a subclass of ProtocolSwitchCommand. @param newProto: the new protocol instance to switch to. @param clientFactory: the ClientFactory to send the L{twisted.internet.protocol.ClientFactory.clientConnectionLost} notification to. """ # All the data that Int16Receiver has not yet dealt with belongs to our # new protocol: luckily it's keeping that in a handy (although # ostensibly internal) variable for us: newProtoData = self.recvd # We're quite possibly in the middle of a 'dataReceived' loop in # Int16StringReceiver: let's make sure that the next iteration, the # loop will break and not attempt to look at something that isn't a # length prefix. self.recvd = '' # Finally, do the actual work of setting up the protocol and delivering # its first chunk of data, if one is available. self.innerProtocol = newProto self.innerProtocolClientFactory = clientFactory newProto.makeConnection(self.transport) if newProtoData: newProto.dataReceived(newProtoData)
Switch this BinaryBoxProtocol's transport to a new protocol. You need to do this 'simultaneously' on both ends of a connection; the easiest way to do this is to use a subclass of ProtocolSwitchCommand. @param newProto: the new protocol instance to switch to. @param clientFactory: the ClientFactory to send the L{twisted.internet.protocol.ClientFactory.clientConnectionLost} notification to.
_switchTo
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def sendBox(self, box): """ Send a amp.Box to my peer. Note: transport.write is never called outside of this method. @param box: an AmpBox. @raise ProtocolSwitched: if the protocol has previously been switched. @raise ConnectionLost: if the connection has previously been lost. """ if self._locked: raise ProtocolSwitched( "This connection has switched: no AMP traffic allowed.") if self.transport is None: raise ConnectionLost() if self._startingTLSBuffer is not None: self._startingTLSBuffer.append(box) else: self.transport.write(box.serialize())
Send a amp.Box to my peer. Note: transport.write is never called outside of this method. @param box: an AmpBox. @raise ProtocolSwitched: if the protocol has previously been switched. @raise ConnectionLost: if the connection has previously been lost.
sendBox
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def makeConnection(self, transport): """ Notify L{boxReceiver} that it is about to receive boxes from this protocol by invoking L{IBoxReceiver.startReceivingBoxes}. """ self.transport = transport self.boxReceiver.startReceivingBoxes(self) self.connectionMade()
Notify L{boxReceiver} that it is about to receive boxes from this protocol by invoking L{IBoxReceiver.startReceivingBoxes}.
makeConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def dataReceived(self, data): """ Either parse incoming data as L{AmpBox}es or relay it to our nested protocol. """ if self._justStartedTLS: self._justStartedTLS = False # If we already have an inner protocol, then we don't deliver data to # the protocol parser any more; we just hand it off. if self.innerProtocol is not None: self.innerProtocol.dataReceived(data) return return Int16StringReceiver.dataReceived(self, data)
Either parse incoming data as L{AmpBox}es or relay it to our nested protocol.
dataReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def connectionLost(self, reason): """ The connection was lost; notify any nested protocol. """ if self.innerProtocol is not None: self.innerProtocol.connectionLost(reason) if self.innerProtocolClientFactory is not None: self.innerProtocolClientFactory.clientConnectionLost(None, reason) if self._keyLengthLimitExceeded: failReason = Failure(TooLong(True, False, None, None)) elif reason.check(ConnectionClosed) and self._justStartedTLS: # We just started TLS and haven't received any data. This means # the other connection didn't like our cert (although they may not # have told us why - later Twisted should make 'reason' into a TLS # error.) failReason = PeerVerifyError( "Peer rejected our certificate for an unknown reason.") else: failReason = reason self.boxReceiver.stopReceivingBoxes(failReason)
The connection was lost; notify any nested protocol.
connectionLost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def proto_init(self, string): """ String received in the 'init' state. """ self._currentBox = AmpBox() return self.proto_key(string)
String received in the 'init' state.
proto_init
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def proto_key(self, string): """ String received in the 'key' state. If the key is empty, a complete box has been received. """ if string: self._currentKey = string self.MAX_LENGTH = self._MAX_VALUE_LENGTH return 'value' else: self.boxReceiver.ampBoxReceived(self._currentBox) self._currentBox = None return 'init'
String received in the 'key' state. If the key is empty, a complete box has been received.
proto_key
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def proto_value(self, string): """ String received in the 'value' state. """ self._currentBox[self._currentKey] = string self._currentKey = None self.MAX_LENGTH = self._MAX_KEY_LENGTH return 'key'
String received in the 'value' state.
proto_value
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def lengthLimitExceeded(self, length): """ The key length limit was exceeded. Disconnect the transport and make sure a meaningful exception is reported. """ self._keyLengthLimitExceeded = True self.transport.loseConnection()
The key length limit was exceeded. Disconnect the transport and make sure a meaningful exception is reported.
lengthLimitExceeded
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _lockForSwitch(self): """ Lock this binary protocol so that no further boxes may be sent. This is used when sending a request to switch underlying protocols. You probably want to subclass ProtocolSwitchCommand rather than calling this directly. """ self._locked = True
Lock this binary protocol so that no further boxes may be sent. This is used when sending a request to switch underlying protocols. You probably want to subclass ProtocolSwitchCommand rather than calling this directly.
_lockForSwitch
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _unlockFromSwitch(self): """ Unlock this locked binary protocol so that further boxes may be sent again. This is used after an attempt to switch protocols has failed for some reason. """ if self.innerProtocol is not None: raise ProtocolSwitched("Protocol already switched. Cannot unlock.") self._locked = False
Unlock this locked binary protocol so that further boxes may be sent again. This is used after an attempt to switch protocols has failed for some reason.
_unlockFromSwitch
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _prepareTLS(self, certificate, verifyAuthorities): """ Used by StartTLSCommand to put us into the state where we don't actually send things that get sent, instead we buffer them. see L{_sendBoxCommand}. """ self._startingTLSBuffer = [] if self.hostCertificate is not None: raise OnlyOneTLS( "Previously authenticated connection between %s and %s " "is trying to re-establish as %s" % ( self.hostCertificate, self.peerCertificate, (certificate, verifyAuthorities)))
Used by StartTLSCommand to put us into the state where we don't actually send things that get sent, instead we buffer them. see L{_sendBoxCommand}.
_prepareTLS
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _startTLS(self, certificate, verifyAuthorities): """ Used by TLSBox to initiate the SSL handshake. @param certificate: a L{twisted.internet.ssl.PrivateCertificate} for use locally. @param verifyAuthorities: L{twisted.internet.ssl.Certificate} instances representing certificate authorities which will verify our peer. """ self.hostCertificate = certificate self._justStartedTLS = True if verifyAuthorities is None: verifyAuthorities = () self.transport.startTLS(certificate.options(*verifyAuthorities)) stlsb = self._startingTLSBuffer if stlsb is not None: self._startingTLSBuffer = None for box in stlsb: self.sendBox(box)
Used by TLSBox to initiate the SSL handshake. @param certificate: a L{twisted.internet.ssl.PrivateCertificate} for use locally. @param verifyAuthorities: L{twisted.internet.ssl.Certificate} instances representing certificate authorities which will verify our peer.
_startTLS
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def unhandledError(self, failure): """ The buck stops here. This error was completely unhandled, time to terminate the connection. """ log.err( failure, "Amp server or network failure unhandled by client application. " "Dropping connection! To avoid, add errbacks to ALL remote " "commands!") if self.transport is not None: self.transport.loseConnection()
The buck stops here. This error was completely unhandled, time to terminate the connection.
unhandledError
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _defaultStartTLSResponder(self): """ The default TLS responder doesn't specify any certificate or anything. From a security perspective, it's little better than a plain-text connection - but it is still a *bit* better, so it's included for convenience. You probably want to override this by providing your own StartTLS.responder. """ return {}
The default TLS responder doesn't specify any certificate or anything. From a security perspective, it's little better than a plain-text connection - but it is still a *bit* better, so it's included for convenience. You probably want to override this by providing your own StartTLS.responder.
_defaultStartTLSResponder
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def locateResponder(self, name): """ Unify the implementations of L{CommandLocator} and L{SimpleStringLocator} to perform both kinds of dispatch, preferring L{CommandLocator}. @type name: C{bytes} """ firstResponder = CommandLocator.locateResponder(self, name) if firstResponder is not None: return firstResponder secondResponder = SimpleStringLocator.locateResponder(self, name) return secondResponder
Unify the implementations of L{CommandLocator} and L{SimpleStringLocator} to perform both kinds of dispatch, preferring L{CommandLocator}. @type name: C{bytes}
locateResponder
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def __repr__(self): """ A verbose string representation which gives us information about this AMP connection. """ if self.innerProtocol is not None: innerRepr = ' inner %r' % (self.innerProtocol,) else: innerRepr = '' return '<%s%s at 0x%x>' % ( self.__class__.__name__, innerRepr, id(self))
A verbose string representation which gives us information about this AMP connection.
__repr__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def makeConnection(self, transport): """ Emit a helpful log message when the connection is made. """ if not self._ampInitialized: # See comment in the constructor re: backward compatibility. I # should probably emit a deprecation warning here. AMP.__init__(self) # Save these so we can emit a similar log message in L{connectionLost}. self._transportPeer = transport.getPeer() self._transportHost = transport.getHost() log.msg("%s connection established (HOST:%s PEER:%s)" % ( self.__class__.__name__, self._transportHost, self._transportPeer)) BinaryBoxProtocol.makeConnection(self, transport)
Emit a helpful log message when the connection is made.
makeConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def connectionLost(self, reason): """ Emit a helpful log message when the connection is lost. """ log.msg("%s connection lost (HOST:%s PEER:%s)" % (self.__class__.__name__, self._transportHost, self._transportPeer)) BinaryBoxProtocol.connectionLost(self, reason) self.transport = None
Emit a helpful log message when the connection is lost.
connectionLost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def startReceivingBoxes(self, sender): """ No initialization is required. """
No initialization is required.
startReceivingBoxes
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def parse(cls, fileObj): """ Parse some amp data stored in a file. @param fileObj: a file-like object. @return: a list of AmpBoxes encoded in the given file. """ parserHelper = cls() bbp = BinaryBoxProtocol(boxReceiver=parserHelper) bbp.makeConnection(parserHelper) bbp.dataReceived(fileObj.read()) return parserHelper.boxes
Parse some amp data stored in a file. @param fileObj: a file-like object. @return: a list of AmpBoxes encoded in the given file.
parse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def parseString(cls, data): """ Parse some amp data stored in a string. @param data: a str holding some amp-encoded data. @return: a list of AmpBoxes encoded in the given string. """ return cls.parse(BytesIO(data))
Parse some amp data stored in a string. @param data: a str holding some amp-encoded data. @return: a list of AmpBoxes encoded in the given string.
parseString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _stringsToObjects(strings, arglist, proto): """ Convert an AmpBox to a dictionary of python objects, converting through a given arglist. @param strings: an AmpBox (or dict of strings) @param arglist: a list of 2-tuples of strings and Argument objects, as described in L{Command.arguments}. @param proto: an L{AMP} instance. @return: the converted dictionary mapping names to argument objects. """ objects = {} myStrings = strings.copy() for argname, argparser in arglist: argparser.fromBox(argname, myStrings, objects, proto) return objects
Convert an AmpBox to a dictionary of python objects, converting through a given arglist. @param strings: an AmpBox (or dict of strings) @param arglist: a list of 2-tuples of strings and Argument objects, as described in L{Command.arguments}. @param proto: an L{AMP} instance. @return: the converted dictionary mapping names to argument objects.
_stringsToObjects
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def _objectsToStrings(objects, arglist, strings, proto): """ Convert a dictionary of python objects to an AmpBox, converting through a given arglist. @param objects: a dict mapping names to python objects @param arglist: a list of 2-tuples of strings and Argument objects, as described in L{Command.arguments}. @param strings: [OUT PARAMETER] An object providing the L{dict} interface which will be populated with serialized data. @param proto: an L{AMP} instance. @return: The converted dictionary mapping names to encoded argument strings (identical to C{strings}). """ myObjects = objects.copy() for argname, argparser in arglist: argparser.toBox(argname, strings, myObjects, proto) return strings
Convert a dictionary of python objects to an AmpBox, converting through a given arglist. @param objects: a dict mapping names to python objects @param arglist: a list of 2-tuples of strings and Argument objects, as described in L{Command.arguments}. @param strings: [OUT PARAMETER] An object providing the L{dict} interface which will be populated with serialized data. @param proto: an L{AMP} instance. @return: The converted dictionary mapping names to encoded argument strings (identical to C{strings}).
_objectsToStrings
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def toString(self, inObject): """ Serialize a C{decimal.Decimal} instance to the specified wire format. """ if isinstance(inObject, decimal.Decimal): # Hopefully decimal.Decimal.__str__ actually does what we want. return str(inObject).encode("ascii") raise ValueError( "amp.Decimal can only encode instances of decimal.Decimal")
Serialize a C{decimal.Decimal} instance to the specified wire format.
toString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def fromString(self, s): """ Parse a string containing a date and time in the wire format into a C{datetime.datetime} instance. """ s = nativeString(s) if len(s) != 32: raise ValueError('invalid date format %r' % (s,)) values = [int(s[p]) for p in self._positions] sign = s[26] timezone = _FixedOffsetTZInfo.fromSignHoursMinutes(sign, *values[7:]) values[7:] = [timezone] return datetime.datetime(*values)
Parse a string containing a date and time in the wire format into a C{datetime.datetime} instance.
fromString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def toString(self, i): """ Serialize a C{datetime.datetime} instance to a string in the specified wire format. """ offset = i.utcoffset() if offset is None: raise ValueError( 'amp.DateTime cannot serialize naive datetime instances. ' 'You may find amp.utc useful.') minutesOffset = (offset.days * 86400 + offset.seconds) // 60 if minutesOffset > 0: sign = '+' else: sign = '-' # strftime has no way to format the microseconds, or put a ':' in the # timezone. Surprise! # Python 3.4 cannot do % interpolation on byte strings so we pack into # an explicitly Unicode string then encode as ASCII. packed = u'%04i-%02i-%02iT%02i:%02i:%02i.%06i%s%02i:%02i' % ( i.year, i.month, i.day, i.hour, i.minute, i.second, i.microsecond, sign, abs(minutesOffset) // 60, abs(minutesOffset) % 60) return packed.encode("ascii")
Serialize a C{datetime.datetime} instance to a string in the specified wire format.
toString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/amp.py
MIT
def getQuote(self): """ Return a quote. May be overrriden in subclasses. """ return b"An apple a day keeps the doctor away.\r\n"
Return a quote. May be overrriden in subclasses.
getQuote
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/wire.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/wire.py
MIT
def getUsers(self): """ Return active users. Override in subclasses. """ return b"root\r\n"
Return active users. Override in subclasses.
getUsers
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/wire.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/wire.py
MIT
def abortConnection(self): """ Abort the connection. Same as L{loseConnection}. """ self.loseConnection()
Abort the connection. Same as L{loseConnection}.
abortConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
MIT
def identityPumpPolicy(queue, target): """ L{identityPumpPolicy} is a policy which delivers each chunk of data written to the given queue as-is to the target. This isn't a particularly realistic policy. @see: L{loopbackAsync} """ while queue: bytes = queue.get() if bytes is None: break target.dataReceived(bytes)
L{identityPumpPolicy} is a policy which delivers each chunk of data written to the given queue as-is to the target. This isn't a particularly realistic policy. @see: L{loopbackAsync}
identityPumpPolicy
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
MIT
def collapsingPumpPolicy(queue, target): """ L{collapsingPumpPolicy} is a policy which collapses all outstanding chunks into a single string and delivers it to the target. @see: L{loopbackAsync} """ bytes = [] while queue: chunk = queue.get() if chunk is None: break bytes.append(chunk) if bytes: target.dataReceived(b''.join(bytes))
L{collapsingPumpPolicy} is a policy which collapses all outstanding chunks into a single string and delivers it to the target. @see: L{loopbackAsync}
collapsingPumpPolicy
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
MIT
def loopbackAsync(server, client, pumpPolicy=identityPumpPolicy): """ Establish a connection between C{server} and C{client} then transfer data between them until the connection is closed. This is often useful for testing a protocol. @param server: The protocol instance representing the server-side of this connection. @param client: The protocol instance representing the client-side of this connection. @param pumpPolicy: When either C{server} or C{client} writes to its transport, the string passed in is added to a queue of data for the other protocol. Eventually, C{pumpPolicy} will be called with one such queue and the corresponding protocol object. The pump policy callable is responsible for emptying the queue and passing the strings it contains to the given protocol's C{dataReceived} method. The signature of C{pumpPolicy} is C{(queue, protocol)}. C{queue} is an object with a C{get} method which will return the next string written to the transport, or L{None} if the transport has been disconnected, and which evaluates to C{True} if and only if there are more items to be retrieved via C{get}. @return: A L{Deferred} which fires when the connection has been closed and both sides have received notification of this. """ serverToClient = _LoopbackQueue() clientToServer = _LoopbackQueue() server.makeConnection(_LoopbackTransport(serverToClient)) client.makeConnection(_LoopbackTransport(clientToServer)) return _loopbackAsyncBody( server, serverToClient, client, clientToServer, pumpPolicy)
Establish a connection between C{server} and C{client} then transfer data between them until the connection is closed. This is often useful for testing a protocol. @param server: The protocol instance representing the server-side of this connection. @param client: The protocol instance representing the client-side of this connection. @param pumpPolicy: When either C{server} or C{client} writes to its transport, the string passed in is added to a queue of data for the other protocol. Eventually, C{pumpPolicy} will be called with one such queue and the corresponding protocol object. The pump policy callable is responsible for emptying the queue and passing the strings it contains to the given protocol's C{dataReceived} method. The signature of C{pumpPolicy} is C{(queue, protocol)}. C{queue} is an object with a C{get} method which will return the next string written to the transport, or L{None} if the transport has been disconnected, and which evaluates to C{True} if and only if there are more items to be retrieved via C{get}. @return: A L{Deferred} which fires when the connection has been closed and both sides have received notification of this.
loopbackAsync
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
MIT
def _loopbackAsyncBody(server, serverToClient, client, clientToServer, pumpPolicy): """ Transfer bytes from the output queue of each protocol to the input of the other. @param server: The protocol instance representing the server-side of this connection. @param serverToClient: The L{_LoopbackQueue} holding the server's output. @param client: The protocol instance representing the client-side of this connection. @param clientToServer: The L{_LoopbackQueue} holding the client's output. @param pumpPolicy: See L{loopbackAsync}. @return: A L{Deferred} which fires when the connection has been closed and both sides have received notification of this. """ def pump(source, q, target): sent = False if q: pumpPolicy(q, target) sent = True if sent and not q: # A write buffer has now been emptied. Give any producer on that # side an opportunity to produce more data. source.transport._pollProducer() return sent while 1: disconnect = clientSent = serverSent = False # Deliver the data which has been written. serverSent = pump(server, serverToClient, client) clientSent = pump(client, clientToServer, server) if not clientSent and not serverSent: # Neither side wrote any data. Wait for some new data to be added # before trying to do anything further. d = defer.Deferred() clientToServer._notificationDeferred = d serverToClient._notificationDeferred = d d.addCallback( _loopbackAsyncContinue, server, serverToClient, client, clientToServer, pumpPolicy) return d if serverToClient.disconnect: # The server wants to drop the connection. Flush any remaining # data it has. disconnect = True pump(server, serverToClient, client) elif clientToServer.disconnect: # The client wants to drop the connection. Flush any remaining # data it has. disconnect = True pump(client, clientToServer, server) if disconnect: # Someone wanted to disconnect, so okay, the connection is gone. server.connectionLost(failure.Failure(main.CONNECTION_DONE)) client.connectionLost(failure.Failure(main.CONNECTION_DONE)) return defer.succeed(None)
Transfer bytes from the output queue of each protocol to the input of the other. @param server: The protocol instance representing the server-side of this connection. @param serverToClient: The L{_LoopbackQueue} holding the server's output. @param client: The protocol instance representing the client-side of this connection. @param clientToServer: The L{_LoopbackQueue} holding the client's output. @param pumpPolicy: See L{loopbackAsync}. @return: A L{Deferred} which fires when the connection has been closed and both sides have received notification of this.
_loopbackAsyncBody
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
MIT
def loopbackTCP(server, client, port=0, noisy=True): """Run session between server and client protocol instances over TCP.""" from twisted.internet import reactor f = policies.WrappingFactory(protocol.Factory()) serverWrapper = _FireOnClose(f, server) f.noisy = noisy f.buildProtocol = lambda addr: serverWrapper serverPort = reactor.listenTCP(port, f, interface='127.0.0.1') clientF = LoopbackClientFactory(client) clientF.noisy = noisy reactor.connectTCP('127.0.0.1', serverPort.getHost().port, clientF) d = clientF.deferred d.addCallback(lambda x: serverWrapper.deferred) d.addCallback(lambda x: serverPort.stopListening()) return d
Run session between server and client protocol instances over TCP.
loopbackTCP
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
MIT
def loopbackUNIX(server, client, noisy=True): """Run session between server and client protocol instances over UNIX socket.""" path = tempfile.mktemp() from twisted.internet import reactor f = policies.WrappingFactory(protocol.Factory()) serverWrapper = _FireOnClose(f, server) f.noisy = noisy f.buildProtocol = lambda addr: serverWrapper serverPort = reactor.listenUNIX(path, f) clientF = LoopbackClientFactory(client) clientF.noisy = noisy reactor.connectUNIX(path, clientF) d = clientF.deferred d.addCallback(lambda x: serverWrapper.deferred) d.addCallback(lambda x: serverPort.stopListening()) return d
Run session between server and client protocol instances over UNIX socket.
loopbackUNIX
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/loopback.py
MIT
def makeConnection(self, transport): """ Initializes the protocol. """ protocol.Protocol.makeConnection(self, transport) self._remainingData = b"" self._currentPayloadSize = 0 self._payload = BytesIO() self._state = self._PARSING_LENGTH self._expectedPayloadSize = 0 self.brokenPeer = 0
Initializes the protocol.
makeConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/basic.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/basic.py
MIT
def sendString(self, string): """ Sends a netstring. Wraps up C{string} by adding length information and a trailing comma; writes the result to the transport. @param string: The string to send. The necessary framing (length prefix, etc) will be added. @type string: C{bytes} """ self.transport.write(_formatNetstring(string))
Sends a netstring. Wraps up C{string} by adding length information and a trailing comma; writes the result to the transport. @param string: The string to send. The necessary framing (length prefix, etc) will be added. @type string: C{bytes}
sendString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/basic.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/basic.py
MIT
def dataReceived(self, data): """ Receives some characters of a netstring. Whenever a complete netstring is received, this method extracts its payload and calls L{stringReceived} to process it. @param data: A chunk of data representing a (possibly partial) netstring @type data: C{bytes} """ self._remainingData += data while self._remainingData: try: self._consumeData() except IncompleteNetstring: break except NetstringParseError: self._handleParseError() break
Receives some characters of a netstring. Whenever a complete netstring is received, this method extracts its payload and calls L{stringReceived} to process it. @param data: A chunk of data representing a (possibly partial) netstring @type data: C{bytes}
dataReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/basic.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/basic.py
MIT
def stringReceived(self, string): """ Override this for notification when each complete string is received. @param string: The complete string which was received with all framing (length prefix, etc) removed. @type string: C{bytes} @raise NotImplementedError: because the method has to be implemented by the child class. """ raise NotImplementedError()
Override this for notification when each complete string is received. @param string: The complete string which was received with all framing (length prefix, etc) removed. @type string: C{bytes} @raise NotImplementedError: because the method has to be implemented by the child class.
stringReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/basic.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/basic.py
MIT
def _maxLengthSize(self): """ Calculate and return the string size of C{self.MAX_LENGTH}. @return: The size of the string representation for C{self.MAX_LENGTH} @rtype: C{float} """ return math.ceil(math.log10(self.MAX_LENGTH)) + 1
Calculate and return the string size of C{self.MAX_LENGTH}. @return: The size of the string representation for C{self.MAX_LENGTH} @rtype: C{float}
_maxLengthSize
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/basic.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/basic.py
MIT