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 _consumeData(self):
"""
Consumes the content of C{self._remainingData}.
@raise IncompleteNetstring: if C{self._remainingData} does not
contain enough data to complete the current netstring.
@raise NetstringParseError: if the received data do not
form a valid netstring.
"""
if self._state == self._PARSING_LENGTH:
self._consumeLength()
self._prepareForPayloadConsumption()
if self._state == self._PARSING_PAYLOAD:
self._consumePayload() | Consumes the content of C{self._remainingData}.
@raise IncompleteNetstring: if C{self._remainingData} does not
contain enough data to complete the current netstring.
@raise NetstringParseError: if the received data do not
form a valid netstring. | _consumeData | 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 _consumeLength(self):
"""
Consumes the length portion of C{self._remainingData}.
@raise IncompleteNetstring: if C{self._remainingData} contains
a partial length specification (digits without trailing
comma).
@raise NetstringParseError: if the received data do not form a valid
netstring.
"""
lengthMatch = self._LENGTH.match(self._remainingData)
if not lengthMatch:
self._checkPartialLengthSpecification()
raise IncompleteNetstring()
self._processLength(lengthMatch) | Consumes the length portion of C{self._remainingData}.
@raise IncompleteNetstring: if C{self._remainingData} contains
a partial length specification (digits without trailing
comma).
@raise NetstringParseError: if the received data do not form a valid
netstring. | _consumeLength | 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 _checkPartialLengthSpecification(self):
"""
Makes sure that the received data represents a valid number.
Checks if C{self._remainingData} represents a number smaller or
equal to C{self.MAX_LENGTH}.
@raise NetstringParseError: if C{self._remainingData} is no
number or is too big (checked by L{_extractLength}).
"""
partialLengthMatch = self._LENGTH_PREFIX.match(self._remainingData)
if not partialLengthMatch:
raise NetstringParseError(self._MISSING_LENGTH)
lengthSpecification = (partialLengthMatch.group(1))
self._extractLength(lengthSpecification) | Makes sure that the received data represents a valid number.
Checks if C{self._remainingData} represents a number smaller or
equal to C{self.MAX_LENGTH}.
@raise NetstringParseError: if C{self._remainingData} is no
number or is too big (checked by L{_extractLength}). | _checkPartialLengthSpecification | 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 _processLength(self, lengthMatch):
"""
Processes the length definition of a netstring.
Extracts and stores in C{self._expectedPayloadSize} the number
representing the netstring size. Removes the prefix
representing the length specification from
C{self._remainingData}.
@raise NetstringParseError: if the received netstring does not
start with a number or the number is bigger than
C{self.MAX_LENGTH}.
@param lengthMatch: A regular expression match object matching
a netstring length specification
@type lengthMatch: C{re.Match}
"""
endOfNumber = lengthMatch.end(1)
startOfData = lengthMatch.end(2)
lengthString = self._remainingData[:endOfNumber]
# Expect payload plus trailing comma:
self._expectedPayloadSize = self._extractLength(lengthString) + 1
self._remainingData = self._remainingData[startOfData:] | Processes the length definition of a netstring.
Extracts and stores in C{self._expectedPayloadSize} the number
representing the netstring size. Removes the prefix
representing the length specification from
C{self._remainingData}.
@raise NetstringParseError: if the received netstring does not
start with a number or the number is bigger than
C{self.MAX_LENGTH}.
@param lengthMatch: A regular expression match object matching
a netstring length specification
@type lengthMatch: C{re.Match} | _processLength | 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 _extractLength(self, lengthAsString):
"""
Attempts to extract the length information of a netstring.
@raise NetstringParseError: if the number is bigger than
C{self.MAX_LENGTH}.
@param lengthAsString: A chunk of data starting with a length
specification
@type lengthAsString: C{bytes}
@return: The length of the netstring
@rtype: C{int}
"""
self._checkStringSize(lengthAsString)
length = int(lengthAsString)
if length > self.MAX_LENGTH:
raise NetstringParseError(self._TOO_LONG % (self.MAX_LENGTH,))
return length | Attempts to extract the length information of a netstring.
@raise NetstringParseError: if the number is bigger than
C{self.MAX_LENGTH}.
@param lengthAsString: A chunk of data starting with a length
specification
@type lengthAsString: C{bytes}
@return: The length of the netstring
@rtype: C{int} | _extractLength | 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 _checkStringSize(self, lengthAsString):
"""
Checks the sanity of lengthAsString.
Checks if the size of the length specification exceeds the
size of the string representing self.MAX_LENGTH. If this is
not the case, the number represented by lengthAsString is
certainly bigger than self.MAX_LENGTH, and a
NetstringParseError can be raised.
This method should make sure that netstrings with extremely
long length specifications are refused before even attempting
to convert them to an integer (which might trigger a
MemoryError).
"""
if len(lengthAsString) > self._maxLengthSize():
raise NetstringParseError(self._TOO_LONG % (self.MAX_LENGTH,)) | Checks the sanity of lengthAsString.
Checks if the size of the length specification exceeds the
size of the string representing self.MAX_LENGTH. If this is
not the case, the number represented by lengthAsString is
certainly bigger than self.MAX_LENGTH, and a
NetstringParseError can be raised.
This method should make sure that netstrings with extremely
long length specifications are refused before even attempting
to convert them to an integer (which might trigger a
MemoryError). | _checkStringSize | 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 _prepareForPayloadConsumption(self):
"""
Sets up variables necessary for consuming the payload of a netstring.
"""
self._state = self._PARSING_PAYLOAD
self._currentPayloadSize = 0
self._payload.seek(0)
self._payload.truncate() | Sets up variables necessary for consuming the payload of a netstring. | _prepareForPayloadConsumption | 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 _consumePayload(self):
"""
Consumes the payload portion of C{self._remainingData}.
If the payload is complete, checks for the trailing comma and
processes the payload. If not, raises an L{IncompleteNetstring}
exception.
@raise IncompleteNetstring: if the payload received so far
contains fewer characters than expected.
@raise NetstringParseError: if the payload does not end with a
comma.
"""
self._extractPayload()
if self._currentPayloadSize < self._expectedPayloadSize:
raise IncompleteNetstring()
self._checkForTrailingComma()
self._state = self._PARSING_LENGTH
self._processPayload() | Consumes the payload portion of C{self._remainingData}.
If the payload is complete, checks for the trailing comma and
processes the payload. If not, raises an L{IncompleteNetstring}
exception.
@raise IncompleteNetstring: if the payload received so far
contains fewer characters than expected.
@raise NetstringParseError: if the payload does not end with a
comma. | _consumePayload | 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 _extractPayload(self):
"""
Extracts payload information from C{self._remainingData}.
Splits C{self._remainingData} at the end of the netstring. The
first part becomes C{self._payload}, the second part is stored
in C{self._remainingData}.
If the netstring is not yet complete, the whole content of
C{self._remainingData} is moved to C{self._payload}.
"""
if self._payloadComplete():
remainingPayloadSize = (self._expectedPayloadSize -
self._currentPayloadSize)
self._payload.write(self._remainingData[:remainingPayloadSize])
self._remainingData = self._remainingData[remainingPayloadSize:]
self._currentPayloadSize = self._expectedPayloadSize
else:
self._payload.write(self._remainingData)
self._currentPayloadSize += len(self._remainingData)
self._remainingData = b"" | Extracts payload information from C{self._remainingData}.
Splits C{self._remainingData} at the end of the netstring. The
first part becomes C{self._payload}, the second part is stored
in C{self._remainingData}.
If the netstring is not yet complete, the whole content of
C{self._remainingData} is moved to C{self._payload}. | _extractPayload | 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 _payloadComplete(self):
"""
Checks if enough data have been received to complete the netstring.
@return: C{True} iff the received data contain at least as many
characters as specified in the length section of the
netstring
@rtype: C{bool}
"""
return (len(self._remainingData) + self._currentPayloadSize >=
self._expectedPayloadSize) | Checks if enough data have been received to complete the netstring.
@return: C{True} iff the received data contain at least as many
characters as specified in the length section of the
netstring
@rtype: C{bool} | _payloadComplete | 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 _processPayload(self):
"""
Processes the actual payload with L{stringReceived}.
Strips C{self._payload} of the trailing comma and calls
L{stringReceived} with the result.
"""
self.stringReceived(self._payload.getvalue()[:-1]) | Processes the actual payload with L{stringReceived}.
Strips C{self._payload} of the trailing comma and calls
L{stringReceived} with the result. | _processPayload | 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 _checkForTrailingComma(self):
"""
Checks if the netstring has a trailing comma at the expected position.
@raise NetstringParseError: if the last payload character is
anything but a comma.
"""
if self._payload.getvalue()[-1:] != b",":
raise NetstringParseError(self._MISSING_COMMA) | Checks if the netstring has a trailing comma at the expected position.
@raise NetstringParseError: if the last payload character is
anything but a comma. | _checkForTrailingComma | 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 _handleParseError(self):
"""
Terminates the connection and sets the flag C{self.brokenPeer}.
"""
self.transport.loseConnection()
self.brokenPeer = 1 | Terminates the connection and sets the flag C{self.brokenPeer}. | _handleParseError | 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):
"""
Translates bytes into lines, and calls lineReceived.
"""
lines = (self._buffer+data).split(self.delimiter)
self._buffer = lines.pop(-1)
for line in lines:
if self.transport.disconnecting:
# this is necessary because the transport may be told to lose
# the connection by a line within a larger packet, and it is
# important to disregard all the lines in that packet following
# the one that told it to close.
return
if len(line) > self.MAX_LENGTH:
return self.lineLengthExceeded(line)
else:
self.lineReceived(line)
if len(self._buffer) > self.MAX_LENGTH:
return self.lineLengthExceeded(self._buffer) | Translates bytes into lines, and calls lineReceived. | 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 lineReceived(self, line):
"""
Override this for when each line is received.
@param line: The line which was received with the delimiter removed.
@type line: C{bytes}
"""
raise NotImplementedError | Override this for when each line is received.
@param line: The line which was received with the delimiter removed.
@type line: C{bytes} | lineReceived | 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 sendLine(self, line):
"""
Sends a line to the other end of the connection.
@param line: The line to send, not including the delimiter.
@type line: C{bytes}
"""
return self.transport.writeSequence((line, self.delimiter)) | Sends a line to the other end of the connection.
@param line: The line to send, not including the delimiter.
@type line: C{bytes} | sendLine | 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 lineLengthExceeded(self, line):
"""
Called when the maximum line length has been reached.
Override if it needs to be dealt with in some special way.
"""
return self.transport.loseConnection() | Called when the maximum line length has been reached.
Override if it needs to be dealt with in some special way. | lineLengthExceeded | 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 clearLineBuffer(self):
"""
Clear buffered data.
@return: All of the cleared buffered data.
@rtype: C{bytes}
"""
b, self._buffer = self._buffer, b""
return b | Clear buffered data.
@return: All of the cleared buffered data.
@rtype: C{bytes} | clearLineBuffer | 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):
"""
Protocol.dataReceived.
Translates bytes into lines, and calls lineReceived (or
rawDataReceived, depending on mode.)
"""
if self._busyReceiving:
self._buffer += data
return
try:
self._busyReceiving = True
self._buffer += data
while self._buffer and not self.paused:
if self.line_mode:
try:
line, self._buffer = self._buffer.split(
self.delimiter, 1)
except ValueError:
if len(self._buffer) >= (self.MAX_LENGTH
+ len(self.delimiter)):
line, self._buffer = self._buffer, b''
return self.lineLengthExceeded(line)
return
else:
lineLength = len(line)
if lineLength > self.MAX_LENGTH:
exceeded = line + self.delimiter + self._buffer
self._buffer = b''
return self.lineLengthExceeded(exceeded)
why = self.lineReceived(line)
if (why or self.transport and
self.transport.disconnecting):
return why
else:
data = self._buffer
self._buffer = b''
why = self.rawDataReceived(data)
if why:
return why
finally:
self._busyReceiving = False | Protocol.dataReceived.
Translates bytes into lines, and calls lineReceived (or
rawDataReceived, depending on mode.) | 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 setLineMode(self, extra=b''):
"""
Sets the line-mode of this receiver.
If you are calling this from a rawDataReceived callback,
you can pass in extra unhandled data, and that data will
be parsed for lines. Further data received will be sent
to lineReceived rather than rawDataReceived.
Do not pass extra data if calling this function from
within a lineReceived callback.
"""
self.line_mode = 1
if extra:
return self.dataReceived(extra) | Sets the line-mode of this receiver.
If you are calling this from a rawDataReceived callback,
you can pass in extra unhandled data, and that data will
be parsed for lines. Further data received will be sent
to lineReceived rather than rawDataReceived.
Do not pass extra data if calling this function from
within a lineReceived callback. | setLineMode | 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 setRawMode(self):
"""
Sets the raw mode of this receiver.
Further data received will be sent to rawDataReceived rather
than lineReceived.
"""
self.line_mode = 0 | Sets the raw mode of this receiver.
Further data received will be sent to rawDataReceived rather
than lineReceived. | setRawMode | 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 rawDataReceived(self, data):
"""
Override this for when raw data is received.
"""
raise NotImplementedError | Override this for when raw data is received. | rawDataReceived | 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 lineReceived(self, line):
"""
Override this for when each line is received.
@param line: The line which was received with the delimiter removed.
@type line: C{bytes}
"""
raise NotImplementedError | Override this for when each line is received.
@param line: The line which was received with the delimiter removed.
@type line: C{bytes} | lineReceived | 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 sendLine(self, line):
"""
Sends a line to the other end of the connection.
@param line: The line to send, not including the delimiter.
@type line: C{bytes}
"""
return self.transport.write(line + self.delimiter) | Sends a line to the other end of the connection.
@param line: The line to send, not including the delimiter.
@type line: C{bytes} | sendLine | 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 lineLengthExceeded(self, line):
"""
Called when the maximum line length has been reached.
Override if it needs to be dealt with in some special way.
The argument 'line' contains the remainder of the buffer, starting
with (at least some part) of the line which is too long. This may
be more than one line, or may be only the initial portion of the
line.
"""
return self.transport.loseConnection() | Called when the maximum line length has been reached.
Override if it needs to be dealt with in some special way.
The argument 'line' contains the remainder of the buffer, starting
with (at least some part) of the line which is too long. This may
be more than one line, or may be only the initial portion of the
line. | lineLengthExceeded | 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 | 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} | 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 lengthLimitExceeded(self, length):
"""
Callback invoked when a length prefix greater than C{MAX_LENGTH} is
received. The default implementation disconnects the transport.
Override this.
@param length: The length prefix which was received.
@type length: C{int}
"""
self.transport.loseConnection() | Callback invoked when a length prefix greater than C{MAX_LENGTH} is
received. The default implementation disconnects the transport.
Override this.
@param length: The length prefix which was received.
@type length: C{int} | lengthLimitExceeded | 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):
"""
Convert int prefixed strings into calls to stringReceived.
"""
# Try to minimize string copying (via slices) by keeping one buffer
# containing all the data we have so far and a separate offset into that
# buffer.
alldata = self._unprocessed + data
currentOffset = 0
prefixLength = self.prefixLength
fmt = self.structFormat
self._unprocessed = alldata
while len(alldata) >= (currentOffset + prefixLength) and not self.paused:
messageStart = currentOffset + prefixLength
length, = unpack(fmt, alldata[currentOffset:messageStart])
if length > self.MAX_LENGTH:
self._unprocessed = alldata
self._compatibilityOffset = currentOffset
self.lengthLimitExceeded(length)
return
messageEnd = messageStart + length
if len(alldata) < messageEnd:
break
# Here we have to slice the working buffer so we can send just the
# netstring into the stringReceived callback.
packet = alldata[messageStart:messageEnd]
currentOffset = messageEnd
self._compatibilityOffset = currentOffset
self.stringReceived(packet)
# Check to see if the backwards compat "recvd" attribute got written
# to by application code. If so, drop the current data buffer and
# switch to the new buffer given by that attribute's value.
if 'recvd' in self.__dict__:
alldata = self.__dict__.pop('recvd')
self._unprocessed = alldata
self._compatibilityOffset = currentOffset = 0
if alldata:
continue
return
# Slice off all the data that has been processed, avoiding holding onto
# memory to store it, and update the compatibility attributes to reflect
# that change.
self._unprocessed = alldata[currentOffset:]
self._compatibilityOffset = 0 | Convert int prefixed strings into calls to stringReceived. | 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 sendString(self, string):
"""
Send a prefixed string to the other end of the connection.
@param string: The string to send. The necessary framing (length
prefix, etc) will be added.
@type string: C{bytes}
"""
if len(string) >= 2 ** (8 * self.prefixLength):
raise StringTooLongError(
"Try to send %s bytes whereas maximum is %s" % (
len(string), 2 ** (8 * self.prefixLength)))
self.transport.write(
pack(self.structFormat, len(string)) + string) | Send a prefixed string to the other end of the connection.
@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 stringReceived(self, string):
"""
Choose a protocol phase function and call it.
Call back to the appropriate protocol phase; this begins with
the function C{proto_init} and moves on to C{proto_*} depending on
what each C{proto_*} function returns. (For example, if
C{self.proto_init} returns 'foo', then C{self.proto_foo} will be the
next function called when a protocol message is received.
"""
try:
pto = 'proto_' + self.state
statehandler = getattr(self, pto)
except AttributeError:
log.msg('callback', self.state, 'not found')
else:
self.state = statehandler(string)
if self.state == 'done':
self.transport.loseConnection() | Choose a protocol phase function and call it.
Call back to the appropriate protocol phase; this begins with
the function C{proto_init} and moves on to C{proto_*} depending on
what each C{proto_*} function returns. (For example, if
C{self.proto_init} returns 'foo', then C{self.proto_foo} will be the
next function called when a protocol message is received. | 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 beginFileTransfer(self, file, consumer, transform=None):
"""
Begin transferring a file
@type file: Any file-like object
@param file: The file object to read data from
@type consumer: Any implementor of IConsumer
@param consumer: The object to write data to
@param transform: A callable taking one string argument and returning
the same. All bytes read from the file are passed through this before
being written to the consumer.
@rtype: C{Deferred}
@return: A deferred whose callback will be invoked when the file has
been completely written to the consumer. The last byte written to the
consumer is passed to the callback.
"""
self.file = file
self.consumer = consumer
self.transform = transform
self.deferred = deferred = defer.Deferred()
self.consumer.registerProducer(self, False)
return deferred | Begin transferring a file
@type file: Any file-like object
@param file: The file object to read data from
@type consumer: Any implementor of IConsumer
@param consumer: The object to write data to
@param transform: A callable taking one string argument and returning
the same. All bytes read from the file are passed through this before
being written to the consumer.
@rtype: C{Deferred}
@return: A deferred whose callback will be invoked when the file has
been completely written to the consumer. The last byte written to the
consumer is passed to the callback. | beginFileTransfer | 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 pauseProducing(self):
"""
C{pauseProducing} the underlying producer, if it's not paused.
"""
if self._producerPaused:
return
self._producerPaused = True
self._producer.pauseProducing() | C{pauseProducing} the underlying producer, if it's not paused. | pauseProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def resumeProducing(self):
"""
C{resumeProducing} the underlying producer, if it's paused.
"""
if not self._producerPaused:
return
self._producerPaused = False
self._producer.resumeProducing() | C{resumeProducing} the underlying producer, if it's paused. | resumeProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def stopProducing(self):
"""
C{stopProducing} the underlying producer.
There is only a single source for this event, so it's simply passed
on.
"""
self._producer.stopProducing() | C{stopProducing} the underlying producer.
There is only a single source for this event, so it's simply passed
on. | stopProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def getHandle(self):
"""
Return the L{OpenSSL.SSL.Connection} object being used to encrypt and
decrypt this connection.
This is done for the benefit of L{twisted.internet.ssl.Certificate}'s
C{peerFromTransport} and C{hostFromTransport} methods only. A
different system handle may be returned by future versions of this
method.
"""
return self._tlsConnection | Return the L{OpenSSL.SSL.Connection} object being used to encrypt and
decrypt this connection.
This is done for the benefit of L{twisted.internet.ssl.Certificate}'s
C{peerFromTransport} and C{hostFromTransport} methods only. A
different system handle may be returned by future versions of this
method. | getHandle | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def makeConnection(self, transport):
"""
Connect this wrapper to the given transport and initialize the
necessary L{OpenSSL.SSL.Connection} with a memory BIO.
"""
self._tlsConnection = self.factory._createConnection(self)
self._appSendBuffer = []
# Add interfaces provided by the transport we are wrapping:
for interface in providedBy(transport):
directlyProvides(self, interface)
# Intentionally skip ProtocolWrapper.makeConnection - it might call
# wrappedProtocol.makeConnection, which we want to make conditional.
Protocol.makeConnection(self, transport)
self.factory.registerProtocol(self)
if self._connectWrapped:
# Now that the TLS layer is initialized, notify the application of
# the connection.
ProtocolWrapper.makeConnection(self, transport)
# Now that we ourselves have a transport (initialized by the
# ProtocolWrapper.makeConnection call above), kick off the TLS
# handshake.
self._checkHandshakeStatus() | Connect this wrapper to the given transport and initialize the
necessary L{OpenSSL.SSL.Connection} with a memory BIO. | makeConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def _checkHandshakeStatus(self):
"""
Ask OpenSSL to proceed with a handshake in progress.
Initially, this just sends the ClientHello; after some bytes have been
stuffed in to the C{Connection} object by C{dataReceived}, it will then
respond to any C{Certificate} or C{KeyExchange} messages.
"""
# The connection might already be aborted (eg. by a callback during
# connection setup), so don't even bother trying to handshake in that
# case.
if self._aborted:
return
try:
self._tlsConnection.do_handshake()
except WantReadError:
self._flushSendBIO()
except Error:
self._tlsShutdownFinished(Failure())
else:
self._handshakeDone = True
if IHandshakeListener.providedBy(self.wrappedProtocol):
self.wrappedProtocol.handshakeCompleted() | Ask OpenSSL to proceed with a handshake in progress.
Initially, this just sends the ClientHello; after some bytes have been
stuffed in to the C{Connection} object by C{dataReceived}, it will then
respond to any C{Certificate} or C{KeyExchange} messages. | _checkHandshakeStatus | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def _flushSendBIO(self):
"""
Read any bytes out of the send BIO and write them to the underlying
transport.
"""
try:
bytes = self._tlsConnection.bio_read(2 ** 15)
except WantReadError:
# There may be nothing in the send BIO right now.
pass
else:
self.transport.write(bytes) | Read any bytes out of the send BIO and write them to the underlying
transport. | _flushSendBIO | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def _flushReceiveBIO(self):
"""
Try to receive any application-level bytes which are now available
because of a previous write into the receive BIO. This will take
care of delivering any application-level bytes which are received to
the protocol, as well as handling of the various exceptions which
can come from trying to get such bytes.
"""
# Keep trying this until an error indicates we should stop or we
# close the connection. Looping is necessary to make sure we
# process all of the data which was put into the receive BIO, as
# there is no guarantee that a single recv call will do it all.
while not self._lostTLSConnection:
try:
bytes = self._tlsConnection.recv(2 ** 15)
except WantReadError:
# The newly received bytes might not have been enough to produce
# any application data.
break
except ZeroReturnError:
# TLS has shut down and no more TLS data will be received over
# this connection.
self._shutdownTLS()
# Passing in None means the user protocol's connnectionLost
# will get called with reason from underlying transport:
self._tlsShutdownFinished(None)
except Error:
# Something went pretty wrong. For example, this might be a
# handshake failure during renegotiation (because there were no
# shared ciphers, because a certificate failed to verify, etc).
# TLS can no longer proceed.
failure = Failure()
self._tlsShutdownFinished(failure)
else:
if not self._aborted:
ProtocolWrapper.dataReceived(self, bytes)
# The received bytes might have generated a response which needs to be
# sent now. For example, the handshake involves several round-trip
# exchanges without ever producing application-bytes.
self._flushSendBIO() | Try to receive any application-level bytes which are now available
because of a previous write into the receive BIO. This will take
care of delivering any application-level bytes which are received to
the protocol, as well as handling of the various exceptions which
can come from trying to get such bytes. | _flushReceiveBIO | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def dataReceived(self, bytes):
"""
Deliver any received bytes to the receive BIO and then read and deliver
to the application any application-level data which becomes available
as a result of this.
"""
# Let OpenSSL know some bytes were just received.
self._tlsConnection.bio_write(bytes)
# If we are still waiting for the handshake to complete, try to
# complete the handshake with the bytes we just received.
if not self._handshakeDone:
self._checkHandshakeStatus()
# If the handshake still isn't finished, then we've nothing left to
# do.
if not self._handshakeDone:
return
# If we've any pending writes, this read may have un-blocked them, so
# attempt to unbuffer them into the OpenSSL layer.
if self._appSendBuffer:
self._unbufferPendingWrites()
# Since the handshake is complete, the wire-level bytes we just
# processed might turn into some application-level bytes; try to pull
# those out.
self._flushReceiveBIO() | Deliver any received bytes to the receive BIO and then read and deliver
to the application any application-level data which becomes available
as a result of this. | dataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def _shutdownTLS(self):
"""
Initiate, or reply to, the shutdown handshake of the TLS layer.
"""
try:
shutdownSuccess = self._tlsConnection.shutdown()
except Error:
# Mid-handshake, a call to shutdown() can result in a
# WantWantReadError, or rather an SSL_ERR_WANT_READ; but pyOpenSSL
# doesn't allow us to get at the error. See:
# https://github.com/pyca/pyopenssl/issues/91
shutdownSuccess = False
self._flushSendBIO()
if shutdownSuccess:
# Both sides have shutdown, so we can start closing lower-level
# transport. This will also happen if we haven't started
# negotiation at all yet, in which case shutdown succeeds
# immediately.
self.transport.loseConnection() | Initiate, or reply to, the shutdown handshake of the TLS layer. | _shutdownTLS | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def _tlsShutdownFinished(self, reason):
"""
Called when TLS connection has gone away; tell underlying transport to
disconnect.
@param reason: a L{Failure} whose value is an L{Exception} if we want to
report that failure through to the wrapped protocol's
C{connectionLost}, or L{None} if the C{reason} that
C{connectionLost} should receive should be coming from the
underlying transport.
@type reason: L{Failure} or L{None}
"""
if reason is not None:
# Squash an EOF in violation of the TLS protocol into
# ConnectionLost, so that applications which might run over
# multiple protocols can recognize its type.
if tuple(reason.value.args[:2]) == (-1, 'Unexpected EOF'):
reason = Failure(CONNECTION_LOST)
if self._reason is None:
self._reason = reason
self._lostTLSConnection = True
# We may need to send a TLS alert regarding the nature of the shutdown
# here (for example, why a handshake failed), so always flush our send
# buffer before telling our lower-level transport to go away.
self._flushSendBIO()
# Using loseConnection causes the application protocol's
# connectionLost method to be invoked non-reentrantly, which is always
# a nice feature. However, for error cases (reason != None) we might
# want to use abortConnection when it becomes available. The
# loseConnection call is basically tested by test_handshakeFailure.
# At least one side will need to do it or the test never finishes.
self.transport.loseConnection() | Called when TLS connection has gone away; tell underlying transport to
disconnect.
@param reason: a L{Failure} whose value is an L{Exception} if we want to
report that failure through to the wrapped protocol's
C{connectionLost}, or L{None} if the C{reason} that
C{connectionLost} should receive should be coming from the
underlying transport.
@type reason: L{Failure} or L{None} | _tlsShutdownFinished | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def connectionLost(self, reason):
"""
Handle the possible repetition of calls to this method (due to either
the underlying transport going away or due to an error at the TLS
layer) and make sure the base implementation only gets invoked once.
"""
if not self._lostTLSConnection:
# Tell the TLS connection that it's not going to get any more data
# and give it a chance to finish reading.
self._tlsConnection.bio_shutdown()
self._flushReceiveBIO()
self._lostTLSConnection = True
reason = self._reason or reason
self._reason = None
self.connected = False
ProtocolWrapper.connectionLost(self, reason)
# Breaking reference cycle between self._tlsConnection and self.
self._tlsConnection = None | Handle the possible repetition of calls to this method (due to either
the underlying transport going away or due to an error at the TLS
layer) and make sure the base implementation only gets invoked once. | connectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def loseConnection(self):
"""
Send a TLS close alert and close the underlying connection.
"""
if self.disconnecting or not self.connected:
return
# If connection setup has not finished, OpenSSL 1.0.2f+ will not shut
# down the connection until we write some data to the connection which
# allows the handshake to complete. However, since no data should be
# written after loseConnection, this means we'll be stuck forever
# waiting for shutdown to complete. Instead, we simply abort the
# connection without trying to shut down cleanly:
if not self._handshakeDone and not self._appSendBuffer:
self.abortConnection()
self.disconnecting = True
if not self._appSendBuffer and self._producer is None:
self._shutdownTLS() | Send a TLS close alert and close the underlying connection. | loseConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def abortConnection(self):
"""
Tear down TLS state so that if the connection is aborted mid-handshake
we don't deliver any further data from the application.
"""
self._aborted = True
self.disconnecting = True
self._shutdownTLS()
self.transport.abortConnection() | Tear down TLS state so that if the connection is aborted mid-handshake
we don't deliver any further data from the application. | abortConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def failVerification(self, reason):
"""
Abort the connection during connection setup, giving a reason that
certificate verification failed.
@param reason: The reason that the verification failed; reported to the
application protocol's C{connectionLost} method.
@type reason: L{Failure}
"""
self._reason = reason
self.abortConnection() | Abort the connection during connection setup, giving a reason that
certificate verification failed.
@param reason: The reason that the verification failed; reported to the
application protocol's C{connectionLost} method.
@type reason: L{Failure} | failVerification | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def write(self, bytes):
"""
Process the given application bytes and send any resulting TLS traffic
which arrives in the send BIO.
If C{loseConnection} was called, subsequent calls to C{write} will
drop the bytes on the floor.
"""
if isinstance(bytes, unicode):
raise TypeError("Must write bytes to a TLS transport, not unicode.")
# Writes after loseConnection are not supported, unless a producer has
# been registered, in which case writes can happen until the producer
# is unregistered:
if self.disconnecting and self._producer is None:
return
self._write(bytes) | Process the given application bytes and send any resulting TLS traffic
which arrives in the send BIO.
If C{loseConnection} was called, subsequent calls to C{write} will
drop the bytes on the floor. | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def _bufferedWrite(self, octets):
"""
Put the given octets into L{TLSMemoryBIOProtocol._appSendBuffer}, and
tell any listening producer that it should pause because we are now
buffering.
"""
self._appSendBuffer.append(octets)
if self._producer is not None:
self._producer.pauseProducing() | Put the given octets into L{TLSMemoryBIOProtocol._appSendBuffer}, and
tell any listening producer that it should pause because we are now
buffering. | _bufferedWrite | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def _unbufferPendingWrites(self):
"""
Un-buffer all waiting writes in L{TLSMemoryBIOProtocol._appSendBuffer}.
"""
pendingWrites, self._appSendBuffer = self._appSendBuffer, []
for eachWrite in pendingWrites:
self._write(eachWrite)
if self._appSendBuffer:
# If OpenSSL ran out of buffer space in the Connection on our way
# through the loop earlier and re-buffered any of our outgoing
# writes, then we're done; don't consider any future work.
return
if self._producer is not None:
# If we have a registered producer, let it know that we have some
# more buffer space.
self._producer.resumeProducing()
return
if self.disconnecting:
# Finally, if we have no further buffered data, no producer wants
# to send us more data in the future, and the application told us
# to end the stream, initiate a TLS shutdown.
self._shutdownTLS() | Un-buffer all waiting writes in L{TLSMemoryBIOProtocol._appSendBuffer}. | _unbufferPendingWrites | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def _write(self, bytes):
"""
Process the given application bytes and send any resulting TLS traffic
which arrives in the send BIO.
This may be called by C{dataReceived} with bytes that were buffered
before C{loseConnection} was called, which is why this function
doesn't check for disconnection but accepts the bytes regardless.
"""
if self._lostTLSConnection:
return
# A TLS payload is 16kB max
bufferSize = 2 ** 14
# How far into the input we've gotten so far
alreadySent = 0
while alreadySent < len(bytes):
toSend = bytes[alreadySent:alreadySent + bufferSize]
try:
sent = self._tlsConnection.send(toSend)
except WantReadError:
self._bufferedWrite(bytes[alreadySent:])
break
except Error:
# Pretend TLS connection disconnected, which will trigger
# disconnect of underlying transport. The error will be passed
# to the application protocol's connectionLost method. The
# other SSL implementation doesn't, but losing helpful
# debugging information is a bad idea.
self._tlsShutdownFinished(Failure())
break
else:
# We've successfully handed off the bytes to the OpenSSL
# Connection object.
alreadySent += sent
# See if OpenSSL wants to hand any bytes off to the underlying
# transport as a result.
self._flushSendBIO() | Process the given application bytes and send any resulting TLS traffic
which arrives in the send BIO.
This may be called by C{dataReceived} with bytes that were buffered
before C{loseConnection} was called, which is why this function
doesn't check for disconnection but accepts the bytes regardless. | _write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def writeSequence(self, iovec):
"""
Write a sequence of application bytes by joining them into one string
and passing them to L{write}.
"""
self.write(b"".join(iovec)) | Write a sequence of application bytes by joining them into one string
and passing them to L{write}. | writeSequence | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def negotiatedProtocol(self):
"""
@see: L{INegotiated.negotiatedProtocol}
"""
protocolName = None
try:
# If ALPN is not implemented that's ok, NPN might be.
protocolName = self._tlsConnection.get_alpn_proto_negotiated()
except (NotImplementedError, AttributeError):
pass
if protocolName not in (b'', None):
# A protocol was selected using ALPN.
return protocolName
try:
protocolName = self._tlsConnection.get_next_proto_negotiated()
except (NotImplementedError, AttributeError):
pass
if protocolName != b'':
return protocolName
return None | @see: L{INegotiated.negotiatedProtocol} | negotiatedProtocol | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def __init__(self, oldStyleContextFactory):
"""
Construct a L{_ContextFactoryToConnectionFactory} with a
L{twisted.internet.interfaces.IOpenSSLContextFactory}.
Immediately call C{getContext} on C{oldStyleContextFactory} in order to
force advance parameter checking, since old-style context factories
don't actually check that their arguments to L{OpenSSL} are correct.
@param oldStyleContextFactory: A factory that can produce contexts.
@type oldStyleContextFactory:
L{twisted.internet.interfaces.IOpenSSLContextFactory}
"""
oldStyleContextFactory.getContext()
self._oldStyleContextFactory = oldStyleContextFactory | Construct a L{_ContextFactoryToConnectionFactory} with a
L{twisted.internet.interfaces.IOpenSSLContextFactory}.
Immediately call C{getContext} on C{oldStyleContextFactory} in order to
force advance parameter checking, since old-style context factories
don't actually check that their arguments to L{OpenSSL} are correct.
@param oldStyleContextFactory: A factory that can produce contexts.
@type oldStyleContextFactory:
L{twisted.internet.interfaces.IOpenSSLContextFactory} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def _connectionForTLS(self, protocol):
"""
Create an L{OpenSSL.SSL.Connection} object.
@param protocol: The protocol initiating a TLS connection.
@type protocol: L{TLSMemoryBIOProtocol}
@return: a connection
@rtype: L{OpenSSL.SSL.Connection}
"""
context = self._oldStyleContextFactory.getContext()
return Connection(context, None) | Create an L{OpenSSL.SSL.Connection} object.
@param protocol: The protocol initiating a TLS connection.
@type protocol: L{TLSMemoryBIOProtocol}
@return: a connection
@rtype: L{OpenSSL.SSL.Connection} | _connectionForTLS | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def serverConnectionForTLS(self, protocol):
"""
Construct an OpenSSL server connection from the wrapped old-style
context factory.
@note: Since old-style context factories don't distinguish between
clients and servers, this is exactly the same as
L{_ContextFactoryToConnectionFactory.clientConnectionForTLS}.
@param protocol: The protocol initiating a TLS connection.
@type protocol: L{TLSMemoryBIOProtocol}
@return: a connection
@rtype: L{OpenSSL.SSL.Connection}
"""
return self._connectionForTLS(protocol) | Construct an OpenSSL server connection from the wrapped old-style
context factory.
@note: Since old-style context factories don't distinguish between
clients and servers, this is exactly the same as
L{_ContextFactoryToConnectionFactory.clientConnectionForTLS}.
@param protocol: The protocol initiating a TLS connection.
@type protocol: L{TLSMemoryBIOProtocol}
@return: a connection
@rtype: L{OpenSSL.SSL.Connection} | serverConnectionForTLS | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def clientConnectionForTLS(self, protocol):
"""
Construct an OpenSSL server connection from the wrapped old-style
context factory.
@note: Since old-style context factories don't distinguish between
clients and servers, this is exactly the same as
L{_ContextFactoryToConnectionFactory.serverConnectionForTLS}.
@param protocol: The protocol initiating a TLS connection.
@type protocol: L{TLSMemoryBIOProtocol}
@return: a connection
@rtype: L{OpenSSL.SSL.Connection}
"""
return self._connectionForTLS(protocol) | Construct an OpenSSL server connection from the wrapped old-style
context factory.
@note: Since old-style context factories don't distinguish between
clients and servers, this is exactly the same as
L{_ContextFactoryToConnectionFactory.serverConnectionForTLS}.
@param protocol: The protocol initiating a TLS connection.
@type protocol: L{TLSMemoryBIOProtocol}
@return: a connection
@rtype: L{OpenSSL.SSL.Connection} | clientConnectionForTLS | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def __init__(self, contextFactory, isClient, wrappedFactory):
"""
Create a L{TLSMemoryBIOFactory}.
@param contextFactory: Configuration parameters used to create an
OpenSSL connection. In order of preference, what you should pass
here should be:
1. L{twisted.internet.ssl.CertificateOptions} (if you're
writing a server) or the result of
L{twisted.internet.ssl.optionsForClientTLS} (if you're
writing a client). If you want security you should really
use one of these.
2. If you really want to implement something yourself, supply a
provider of L{IOpenSSLClientConnectionCreator} or
L{IOpenSSLServerConnectionCreator}.
3. If you really have to, supply a
L{twisted.internet.ssl.ContextFactory}. This will likely be
deprecated at some point so please upgrade to the new
interfaces.
@type contextFactory: L{IOpenSSLClientConnectionCreator} or
L{IOpenSSLServerConnectionCreator}, or, for compatibility with
older code, anything implementing
L{twisted.internet.interfaces.IOpenSSLContextFactory}. See
U{https://twistedmatrix.com/trac/ticket/7215} for information on
the upcoming deprecation of passing a
L{twisted.internet.ssl.ContextFactory} here.
@param isClient: Is this a factory for TLS client connections; in other
words, those that will send a C{ClientHello} greeting? L{True} if
so, L{False} otherwise. This flag determines what interface is
expected of C{contextFactory}. If L{True}, C{contextFactory}
should provide L{IOpenSSLClientConnectionCreator}; otherwise it
should provide L{IOpenSSLServerConnectionCreator}.
@type isClient: L{bool}
@param wrappedFactory: A factory which will create the
application-level protocol.
@type wrappedFactory: L{twisted.internet.interfaces.IProtocolFactory}
"""
WrappingFactory.__init__(self, wrappedFactory)
if isClient:
creatorInterface = IOpenSSLClientConnectionCreator
else:
creatorInterface = IOpenSSLServerConnectionCreator
self._creatorInterface = creatorInterface
if not creatorInterface.providedBy(contextFactory):
contextFactory = _ContextFactoryToConnectionFactory(contextFactory)
self._connectionCreator = contextFactory | Create a L{TLSMemoryBIOFactory}.
@param contextFactory: Configuration parameters used to create an
OpenSSL connection. In order of preference, what you should pass
here should be:
1. L{twisted.internet.ssl.CertificateOptions} (if you're
writing a server) or the result of
L{twisted.internet.ssl.optionsForClientTLS} (if you're
writing a client). If you want security you should really
use one of these.
2. If you really want to implement something yourself, supply a
provider of L{IOpenSSLClientConnectionCreator} or
L{IOpenSSLServerConnectionCreator}.
3. If you really have to, supply a
L{twisted.internet.ssl.ContextFactory}. This will likely be
deprecated at some point so please upgrade to the new
interfaces.
@type contextFactory: L{IOpenSSLClientConnectionCreator} or
L{IOpenSSLServerConnectionCreator}, or, for compatibility with
older code, anything implementing
L{twisted.internet.interfaces.IOpenSSLContextFactory}. See
U{https://twistedmatrix.com/trac/ticket/7215} for information on
the upcoming deprecation of passing a
L{twisted.internet.ssl.ContextFactory} here.
@param isClient: Is this a factory for TLS client connections; in other
words, those that will send a C{ClientHello} greeting? L{True} if
so, L{False} otherwise. This flag determines what interface is
expected of C{contextFactory}. If L{True}, C{contextFactory}
should provide L{IOpenSSLClientConnectionCreator}; otherwise it
should provide L{IOpenSSLServerConnectionCreator}.
@type isClient: L{bool}
@param wrappedFactory: A factory which will create the
application-level protocol.
@type wrappedFactory: L{twisted.internet.interfaces.IProtocolFactory} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def logPrefix(self):
"""
Annotate the wrapped factory's log prefix with some text indicating TLS
is in use.
@rtype: C{str}
"""
if ILoggingContext.providedBy(self.wrappedFactory):
logPrefix = self.wrappedFactory.logPrefix()
else:
logPrefix = self.wrappedFactory.__class__.__name__
return "%s (TLS)" % (logPrefix,) | Annotate the wrapped factory's log prefix with some text indicating TLS
is in use.
@rtype: C{str} | logPrefix | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def _applyProtocolNegotiation(self, connection):
"""
Applies ALPN/NPN protocol neogitation to the connection, if the factory
supports it.
@param connection: The OpenSSL connection object to have ALPN/NPN added
to it.
@type connection: L{OpenSSL.SSL.Connection}
@return: Nothing
@rtype: L{None}
"""
if IProtocolNegotiationFactory.providedBy(self.wrappedFactory):
protocols = self.wrappedFactory.acceptableProtocols()
context = connection.get_context()
_setAcceptableProtocols(context, protocols)
return | Applies ALPN/NPN protocol neogitation to the connection, if the factory
supports it.
@param connection: The OpenSSL connection object to have ALPN/NPN added
to it.
@type connection: L{OpenSSL.SSL.Connection}
@return: Nothing
@rtype: L{None} | _applyProtocolNegotiation | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def _createConnection(self, tlsProtocol):
"""
Create an OpenSSL connection and set it up good.
@param tlsProtocol: The protocol which is establishing the connection.
@type tlsProtocol: L{TLSMemoryBIOProtocol}
@return: an OpenSSL connection object for C{tlsProtocol} to use
@rtype: L{OpenSSL.SSL.Connection}
"""
connectionCreator = self._connectionCreator
if self._creatorInterface is IOpenSSLClientConnectionCreator:
connection = connectionCreator.clientConnectionForTLS(tlsProtocol)
self._applyProtocolNegotiation(connection)
connection.set_connect_state()
else:
connection = connectionCreator.serverConnectionForTLS(tlsProtocol)
self._applyProtocolNegotiation(connection)
connection.set_accept_state()
return connection | Create an OpenSSL connection and set it up good.
@param tlsProtocol: The protocol which is establishing the connection.
@type tlsProtocol: L{TLSMemoryBIOProtocol}
@return: an OpenSSL connection object for C{tlsProtocol} to use
@rtype: L{OpenSSL.SSL.Connection} | _createConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/tls.py | MIT |
def dataReceived(self, data):
"""
Called whenever data is received.
@type data: L{bytes}
@param data: Part or all of a SOCKSv4 packet.
"""
if self.otherConn:
self.otherConn.write(data)
return
self.buf = self.buf + data
completeBuffer = self.buf
if b"\000" in self.buf[8:]:
head, self.buf = self.buf[:8], self.buf[8:]
version, code, port = struct.unpack("!BBH", head[:4])
user, self.buf = self.buf.split(b"\000", 1)
if head[4:7] == b"\000\000\000" and head[7:8] != b"\000":
# An IP address of the form 0.0.0.X, where X is non-zero,
# signifies that this is a SOCKSv4a packet.
# If the complete packet hasn't been received, restore the
# buffer and wait for it.
if b"\000" not in self.buf:
self.buf = completeBuffer
return
server, self.buf = self.buf.split(b"\000", 1)
d = self.reactor.resolve(server)
d.addCallback(self._dataReceived2, user,
version, code, port)
d.addErrback(lambda result, self = self: self.makeReply(91))
return
else:
server = socket.inet_ntoa(head[4:8])
self._dataReceived2(server, user, version, code, port) | Called whenever data is received.
@type data: L{bytes}
@param data: Part or all of a SOCKSv4 packet. | dataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/socks.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/socks.py | MIT |
def _dataReceived2(self, server, user, version, code, port):
"""
The second half of the SOCKS connection setup. For a SOCKSv4 packet this
is after the server address has been extracted from the header. For a
SOCKSv4a packet this is after the host name has been resolved.
@type server: L{str}
@param server: The IP address of the destination, represented as a
dotted quad.
@type user: L{str}
@param user: The username associated with the connection.
@type version: L{int}
@param version: The SOCKS protocol version number.
@type code: L{int}
@param code: The comand code. 1 means establish a TCP/IP stream
connection, and 2 means establish a TCP/IP port binding.
@type port: L{int}
@param port: The port number associated with the connection.
"""
assert version == 4, "Bad version code: %s" % version
if not self.authorize(code, server, port, user):
self.makeReply(91)
return
if code == 1: # CONNECT
d = self.connectClass(server, port, SOCKSv4Outgoing, self)
d.addErrback(lambda result, self = self: self.makeReply(91))
elif code == 2: # BIND
d = self.listenClass(0, SOCKSv4IncomingFactory, self, server)
d.addCallback(lambda x,
self = self: self.makeReply(90, 0, x[1], x[0]))
else:
raise RuntimeError("Bad Connect Code: %s" % (code,))
assert self.buf == b"", "hmm, still stuff in buffer... %s" % repr(
self.buf) | The second half of the SOCKS connection setup. For a SOCKSv4 packet this
is after the server address has been extracted from the header. For a
SOCKSv4a packet this is after the host name has been resolved.
@type server: L{str}
@param server: The IP address of the destination, represented as a
dotted quad.
@type user: L{str}
@param user: The username associated with the connection.
@type version: L{int}
@param version: The SOCKS protocol version number.
@type code: L{int}
@param code: The comand code. 1 means establish a TCP/IP stream
connection, and 2 means establish a TCP/IP port binding.
@type port: L{int}
@param port: The port number associated with the connection. | _dataReceived2 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/socks.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/socks.py | MIT |
def parseParam(line):
"""Chew one dqstring or atom from beginning of line and return (param, remaningline)"""
if line == b'':
return (None, b'')
elif line[0:1] != b'"': # atom
mode = 1
else: # dqstring
mode = 2
res = b""
io = BytesIO(line)
if mode == 2: # skip the opening quote
io.read(1)
while 1:
a = io.read(1)
if a == b'"':
if mode == 2:
io.read(1) # skip the separating space
return (res, io.read())
elif a == b'\\':
a = io.read(1)
if a == b'':
return (None, line) # unexpected end of string
elif a == b'':
if mode == 1:
return (res, io.read())
else:
return (None, line) # unexpected end of string
elif a == b' ':
if mode == 1:
return (res, io.read())
res += a | Chew one dqstring or atom from beginning of line and return (param, remaningline) | parseParam | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def makeAtom(line):
"""Munch a string into an 'atom'"""
# FIXME: proper quoting
return filter(lambda x: not (x in map(chr, range(33)+[34, 39, 92])), line) | Munch a string into an 'atom | makeAtom | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def sendLine(self, line):
"""Throw up if the line is longer than 1022 characters"""
if len(line) > self.MAX_LENGTH - 2:
raise ValueError("DictClient tried to send a too long line")
basic.LineReceiver.sendLine(self, line) | Throw up if the line is longer than 1022 characters | sendLine | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_default(self, line):
"""Unknown message"""
log.msg("DictClient got unexpected message from server -- %s" % line)
self.protocolError("Unexpected server message")
self.transport.loseConnection() | Unknown message | dictCode_default | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_221_ready(self, line):
"""We are about to get kicked off, do nothing"""
pass | We are about to get kicked off, do nothing | dictCode_221_ready | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_220_conn(self, line):
"""Greeting message"""
self.state = "ready"
self.dictConnected() | Greeting message | dictCode_220_conn | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def sendDefine(self, database, word):
"""Send a dict DEFINE command"""
assert self.state == "ready", "DictClient.sendDefine called when not in ready state"
self.result = None # these two are just in case. In "ready" state, result and data
self.data = None # should be None
self.state = "define"
command = "DEFINE %s %s" % (makeAtom(database.encode("UTF-8")), makeWord(word.encode("UTF-8")))
self.sendLine(command) | Send a dict DEFINE command | sendDefine | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def sendMatch(self, database, strategy, word):
"""Send a dict MATCH command"""
assert self.state == "ready", "DictClient.sendMatch called when not in ready state"
self.result = None
self.data = None
self.state = "match"
command = "MATCH %s %s %s" % (makeAtom(database), makeAtom(strategy), makeAtom(word))
self.sendLine(command.encode("UTF-8")) | Send a dict MATCH command | sendMatch | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_550_define(self, line):
"""Invalid database"""
self.mode = "ready"
self.defineFailed("Invalid database") | Invalid database | dictCode_550_define | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_550_match(self, line):
"""Invalid database"""
self.mode = "ready"
self.matchFailed("Invalid database") | Invalid database | dictCode_550_match | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_551_match(self, line):
"""Invalid strategy"""
self.mode = "ready"
self.matchFailed("Invalid strategy") | Invalid strategy | dictCode_551_match | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_552_define(self, line):
"""No match"""
self.mode = "ready"
self.defineFailed("No match") | No match | dictCode_552_define | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_552_match(self, line):
"""No match"""
self.mode = "ready"
self.matchFailed("No match") | No match | dictCode_552_match | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_150_define(self, line):
"""n definitions retrieved"""
self.result = [] | n definitions retrieved | dictCode_150_define | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_151_define(self, line):
"""Definition text follows"""
self.mode = "text"
(word, line) = parseParam(line)
(db, line) = parseParam(line)
(dbdesc, line) = parseParam(line)
if not (word and db and dbdesc):
self.protocolError("Invalid server response")
self.transport.loseConnection()
else:
self.result.append(Definition(word, db, dbdesc, []))
self.data = [] | Definition text follows | dictCode_151_define | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_152_match(self, line):
"""n matches found, text follows"""
self.mode = "text"
self.result = []
self.data = [] | n matches found, text follows | dictCode_152_match | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_text_define(self, line):
"""A line of definition text received"""
res = parseText(line)
if res == None:
self.mode = "command"
self.result[-1].text = self.data
self.data = None
else:
self.data.append(line) | A line of definition text received | dictCode_text_define | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_text_match(self, line):
"""One line of match text received"""
def l(s):
p1, t = parseParam(s)
p2, t = parseParam(t)
return (p1, p2)
res = parseText(line)
if res == None:
self.mode = "command"
self.result = map(l, self.data)
self.data = None
else:
self.data.append(line) | One line of match text received | dictCode_text_match | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_250_define(self, line):
"""ok"""
t = self.result
self.result = None
self.state = "ready"
self.defineDone(t) | ok | dictCode_250_define | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictCode_250_match(self, line):
"""ok"""
t = self.result
self.result = None
self.state = "ready"
self.matchDone(t) | ok | dictCode_250_match | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def protocolError(self, reason):
"""override to catch unexpected dict protocol conditions"""
pass | override to catch unexpected dict protocol conditions | protocolError | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def dictConnected(self):
"""override to be notified when the server is ready to accept commands"""
pass | override to be notified when the server is ready to accept commands | dictConnected | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def defineFailed(self, reason):
"""override to catch reasonable failure responses to DEFINE"""
pass | override to catch reasonable failure responses to DEFINE | defineFailed | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def defineDone(self, result):
"""override to catch successful DEFINE"""
pass | override to catch successful DEFINE | defineDone | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def matchFailed(self, reason):
"""override to catch resonable failure responses to MATCH"""
pass | override to catch resonable failure responses to MATCH | matchFailed | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def matchDone(self, result):
"""override to catch successful MATCH"""
pass | override to catch successful MATCH | matchDone | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def clientDone(self):
"""Called by client when done."""
self.done = 1
del self.d | Called by client when done. | clientDone | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def define(host, port, database, word):
"""Look up a word using a dict server"""
d = defer.Deferred()
factory = DictLookupFactory("define", (database, word), d)
from twisted.internet import reactor
reactor.connectTCP(host, port, factory)
return d | Look up a word using a dict server | define | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def match(host, port, database, strategy, word):
"""Match a word using a dict server"""
d = defer.Deferred()
factory = DictLookupFactory("match", (database, strategy, word), d)
from twisted.internet import reactor
reactor.connectTCP(host, port, factory)
return d | Match a word using a dict server | match | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/dict.py | MIT |
def __init__(self, command, **kwargs):
"""
Create a command.
@param command: the name of the command.
@type command: L{bytes}
@param kwargs: this values will be stored as attributes of the object
for future use
"""
self.command = command
self._deferred = Deferred()
for k, v in kwargs.items():
setattr(self, k, v) | Create a command.
@param command: the name of the command.
@type command: L{bytes}
@param kwargs: this values will be stored as attributes of the object
for future use | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | MIT |
def success(self, value):
"""
Shortcut method to fire the underlying deferred.
"""
self._deferred.callback(value) | Shortcut method to fire the underlying deferred. | success | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | MIT |
def fail(self, error):
"""
Make the underlying deferred fails.
"""
self._deferred.errback(error) | Make the underlying deferred fails. | fail | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | MIT |
def __init__(self, timeOut=60):
"""
Create the protocol.
@param timeOut: the timeout to wait before detecting that the
connection is dead and close it. It's expressed in seconds.
@type timeOut: L{int}
"""
self._current = deque()
self._lenExpected = None
self._getBuffer = None
self._bufferLength = None
self.persistentTimeOut = self.timeOut = timeOut | Create the protocol.
@param timeOut: the timeout to wait before detecting that the
connection is dead and close it. It's expressed in seconds.
@type timeOut: L{int} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | MIT |
def _cancelCommands(self, reason):
"""
Cancel all the outstanding commands, making them fail with C{reason}.
"""
while self._current:
cmd = self._current.popleft()
cmd.fail(reason) | Cancel all the outstanding commands, making them fail with C{reason}. | _cancelCommands | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | MIT |
def timeoutConnection(self):
"""
Close the connection in case of timeout.
"""
self._cancelCommands(TimeoutError("Connection timeout"))
self.transport.loseConnection() | Close the connection in case of timeout. | timeoutConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | MIT |
def connectionLost(self, reason):
"""
Cause any outstanding commands to fail.
"""
self._disconnected = True
self._cancelCommands(reason)
LineReceiver.connectionLost(self, reason) | Cause any outstanding commands to fail. | connectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | MIT |
def sendLine(self, line):
"""
Override sendLine to add a timeout to response.
"""
if not self._current:
self.setTimeout(self.persistentTimeOut)
LineReceiver.sendLine(self, line) | Override sendLine to add a timeout to response. | sendLine | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | MIT |
def rawDataReceived(self, data):
"""
Collect data for a get.
"""
self.resetTimeout()
self._getBuffer.append(data)
self._bufferLength += len(data)
if self._bufferLength >= self._lenExpected + 2:
data = b"".join(self._getBuffer)
buf = data[:self._lenExpected]
rem = data[self._lenExpected + 2:]
val = buf
self._lenExpected = None
self._getBuffer = None
self._bufferLength = None
cmd = self._current[0]
if cmd.multiple:
flags, cas = cmd.values[cmd.currentKey]
cmd.values[cmd.currentKey] = (flags, cas, val)
else:
cmd.value = val
self.setLineMode(rem) | Collect data for a get. | rawDataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/protocols/memcache.py | MIT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.