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 loseConnection(self):
"""
Pass the loseConnection through to the underlying channel.
"""
if self.channel is not None:
self.channel.loseConnection() | Pass the loseConnection through to the underlying channel. | loseConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def __eq__(self, other):
"""
Determines if two requests are the same object.
@param other: Another object whose identity will be compared
to this instance's.
@return: L{True} when the two are the same object and L{False}
when not.
@rtype: L{bool}
"""
# When other is not an instance of request, return
# NotImplemented so that Python uses other.__eq__ to perform
# the comparison. This ensures that a Request proxy generated
# by proxyForInterface compares equal to an actual Request
# instanceby turning request != proxy into proxy != request.
if isinstance(other, Request):
return self is other
return NotImplemented | Determines if two requests are the same object.
@param other: Another object whose identity will be compared
to this instance's.
@return: L{True} when the two are the same object and L{False}
when not.
@rtype: L{bool} | __eq__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def __ne__(self, other):
"""
Determines if two requests are not the same object.
@param other: Another object whose identity will be compared
to this instance's.
@return: L{True} when the two are not the same object and
L{False} when they are.
@rtype: L{bool}
"""
# When other is not an instance of request, return
# NotImplemented so that Python uses other.__ne__ to perform
# the comparison. This ensures that a Request proxy generated
# by proxyForInterface can compare equal to an actual Request
# instance by turning request != proxy into proxy != request.
if isinstance(other, Request):
return self is not other
return NotImplemented | Determines if two requests are not the same object.
@param other: Another object whose identity will be compared
to this instance's.
@return: L{True} when the two are not the same object and
L{False} when they are.
@rtype: L{bool} | __ne__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def __hash__(self):
"""
A C{Request} is hashable so that it can be used as a mapping key.
@return: A C{int} based on the instance's identity.
"""
return id(self) | A C{Request} is hashable so that it can be used as a mapping key.
@return: A C{int} based on the instance's identity. | __hash__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def dataReceived(self, data):
"""
Interpret the next chunk of bytes received. Either deliver them to the
data callback or invoke the finish callback if enough bytes have been
received.
@raise RuntimeError: If the finish callback has already been invoked
during a previous call to this methood.
"""
if self.dataCallback is None:
raise RuntimeError(
"_IdentityTransferDecoder cannot decode data after finishing")
if self.contentLength is None:
self.dataCallback(data)
elif len(data) < self.contentLength:
self.contentLength -= len(data)
self.dataCallback(data)
else:
# Make the state consistent before invoking any code belonging to
# anyone else in case noMoreData ends up being called beneath this
# stack frame.
contentLength = self.contentLength
dataCallback = self.dataCallback
finishCallback = self.finishCallback
self.dataCallback = self.finishCallback = None
self.contentLength = 0
dataCallback(data[:contentLength])
finishCallback(data[contentLength:]) | Interpret the next chunk of bytes received. Either deliver them to the
data callback or invoke the finish callback if enough bytes have been
received.
@raise RuntimeError: If the finish callback has already been invoked
during a previous call to this methood. | dataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def noMoreData(self):
"""
All data which will be delivered to this decoder has been. Check to
make sure as much data as was expected has been received.
@raise PotentialDataLoss: If the content length is unknown.
@raise _DataLoss: If the content length is known and fewer than that
many bytes have been delivered.
@return: L{None}
"""
finishCallback = self.finishCallback
self.dataCallback = self.finishCallback = None
if self.contentLength is None:
finishCallback(b'')
raise PotentialDataLoss()
elif self.contentLength != 0:
raise _DataLoss() | All data which will be delivered to this decoder has been. Check to
make sure as much data as was expected has been received.
@raise PotentialDataLoss: If the content length is unknown.
@raise _DataLoss: If the content length is known and fewer than that
many bytes have been delivered.
@return: L{None} | noMoreData | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def dataReceived(self, data):
"""
Interpret data from a request or response body which uses the
I{chunked} Transfer-Encoding.
"""
data = self._buffer + data
self._buffer = b''
while data:
data = getattr(self, '_dataReceived_%s' % (self.state,))(data) | Interpret data from a request or response body which uses the
I{chunked} Transfer-Encoding. | dataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def noMoreData(self):
"""
Verify that all data has been received. If it has not been, raise
L{_DataLoss}.
"""
if self.state != 'FINISHED':
raise _DataLoss(
"Chunked decoder in %r state, still expecting more data to "
"get to 'FINISHED' state." % (self.state,)) | Verify that all data has been received. If it has not been, raise
L{_DataLoss}. | noMoreData | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def pauseProducing(self):
"""
Pause producing data.
Tells a producer that it has produced too much data to process for
the time being, and to stop until resumeProducing() is called.
"""
pass | Pause producing data.
Tells a producer that it has produced too much data to process for
the time being, and to stop until resumeProducing() is called. | pauseProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def resumeProducing(self):
"""
Resume producing data.
This tells a producer to re-add itself to the main loop and produce
more data for its consumer.
"""
pass | Resume producing data.
This tells a producer to re-add itself to the main loop and produce
more data for its consumer. | resumeProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def registerProducer(self, producer, streaming):
"""
Register to receive data from a producer.
@param producer: The producer to register.
@param streaming: Whether this is a streaming producer or not.
"""
pass | Register to receive data from a producer.
@param producer: The producer to register.
@param streaming: Whether this is a streaming producer or not. | registerProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def unregisterProducer(self):
"""
Stop consuming data from a producer, without disconnecting.
"""
pass | Stop consuming data from a producer, without disconnecting. | unregisterProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def lineReceived(self, line):
"""
Called for each line from request until the end of headers when
it enters binary mode.
"""
self.resetTimeout()
self._receivedHeaderSize += len(line)
if (self._receivedHeaderSize > self.totalHeadersSize):
self._respondToBadRequestAndDisconnect()
return
if self.__first_line:
# if this connection is not persistent, drop any data which
# the client (illegally) sent after the last request.
if not self.persistent:
self.dataReceived = self.lineReceived = lambda *args: None
return
# IE sends an extraneous empty line (\r\n) after a POST request;
# eat up such a line, but only ONCE
if not line and self.__first_line == 1:
self.__first_line = 2
return
# create a new Request object
if INonQueuedRequestFactory.providedBy(self.requestFactory):
request = self.requestFactory(self)
else:
request = self.requestFactory(self, len(self.requests))
self.requests.append(request)
self.__first_line = 0
parts = line.split()
if len(parts) != 3:
self._respondToBadRequestAndDisconnect()
return
command, request, version = parts
try:
command.decode("ascii")
except UnicodeDecodeError:
self._respondToBadRequestAndDisconnect()
return
self._command = command
self._path = request
self._version = version
elif line == b'':
# End of headers.
if self.__header:
ok = self.headerReceived(self.__header)
# If the last header we got is invalid, we MUST NOT proceed
# with processing. We'll have sent a 400 anyway, so just stop.
if not ok:
return
self.__header = b''
self.allHeadersReceived()
if self.length == 0:
self.allContentReceived()
else:
self.setRawMode()
elif line[0] in b' \t':
# Continuation of a multi line header.
self.__header = self.__header + b'\n' + line
# Regular header line.
# Processing of header line is delayed to allow accumulating multi
# line headers.
else:
if self.__header:
self.headerReceived(self.__header)
self.__header = line | Called for each line from request until the end of headers when
it enters binary mode. | lineReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def headerReceived(self, line):
"""
Do pre-processing (for content-length) and store this header away.
Enforce the per-request header limit.
@type line: C{bytes}
@param line: A line from the header section of a request, excluding the
line delimiter.
@return: A flag indicating whether the header was valid.
@rtype: L{bool}
"""
try:
header, data = line.split(b':', 1)
except ValueError:
self._respondToBadRequestAndDisconnect()
return False
header = header.lower()
data = data.strip()
if header == b'content-length':
try:
self.length = int(data)
except ValueError:
self._respondToBadRequestAndDisconnect()
self.length = None
return False
self._transferDecoder = _IdentityTransferDecoder(
self.length, self.requests[-1].handleContentChunk, self._finishRequestBody)
elif header == b'transfer-encoding' and data.lower() == b'chunked':
# XXX Rather poorly tested code block, apparently only exercised by
# test_chunkedEncoding
self.length = None
self._transferDecoder = _ChunkedTransferDecoder(
self.requests[-1].handleContentChunk, self._finishRequestBody)
reqHeaders = self.requests[-1].requestHeaders
values = reqHeaders.getRawHeaders(header)
if values is not None:
values.append(data)
else:
reqHeaders.setRawHeaders(header, [data])
self._receivedHeaderCount += 1
if self._receivedHeaderCount > self.maxHeaders:
self._respondToBadRequestAndDisconnect()
return False
return True | Do pre-processing (for content-length) and store this header away.
Enforce the per-request header limit.
@type line: C{bytes}
@param line: A line from the header section of a request, excluding the
line delimiter.
@return: A flag indicating whether the header was valid.
@rtype: L{bool} | headerReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def dataReceived(self, data):
"""
Data was received from the network. Process it.
"""
# If we're currently handling a request, buffer this data.
if self._handlingRequest:
self._dataBuffer.append(data)
if (
(sum(map(len, self._dataBuffer)) >
self._optimisticEagerReadSize)
and not self._waitingForTransport
):
# If we received more data than a small limit while processing
# the head-of-line request, apply TCP backpressure to our peer
# to get them to stop sending more request data until we're
# ready. See docstring for _optimisticEagerReadSize above.
self._networkProducer.pauseProducing()
return
return basic.LineReceiver.dataReceived(self, data) | Data was received from the network. Process it. | dataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def checkPersistence(self, request, version):
"""
Check if the channel should close or not.
@param request: The request most recently received over this channel
against which checks will be made to determine if this connection
can remain open after a matching response is returned.
@type version: C{bytes}
@param version: The version of the request.
@rtype: C{bool}
@return: A flag which, if C{True}, indicates that this connection may
remain open to receive another request; if C{False}, the connection
must be closed in order to indicate the completion of the response
to C{request}.
"""
connection = request.requestHeaders.getRawHeaders(b'connection')
if connection:
tokens = [t.lower() for t in connection[0].split(b' ')]
else:
tokens = []
# Once any HTTP 0.9 or HTTP 1.0 request is received, the connection is
# no longer allowed to be persistent. At this point in processing the
# request, we don't yet know if it will be possible to set a
# Content-Length in the response. If it is not, then the connection
# will have to be closed to end an HTTP 0.9 or HTTP 1.0 response.
# If the checkPersistence call happened later, after the Content-Length
# has been determined (or determined not to be set), it would probably
# be possible to have persistent connections with HTTP 0.9 and HTTP 1.0.
# This may not be worth the effort, though. Just use HTTP 1.1, okay?
if version == b"HTTP/1.1":
if b'close' in tokens:
request.responseHeaders.setRawHeaders(b'connection', [b'close'])
return False
else:
return True
else:
return False | Check if the channel should close or not.
@param request: The request most recently received over this channel
against which checks will be made to determine if this connection
can remain open after a matching response is returned.
@type version: C{bytes}
@param version: The version of the request.
@rtype: C{bool}
@return: A flag which, if C{True}, indicates that this connection may
remain open to receive another request; if C{False}, the connection
must be closed in order to indicate the completion of the response
to C{request}. | checkPersistence | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def requestDone(self, request):
"""
Called by first request in queue when it is done.
"""
if request != self.requests[0]: raise TypeError
del self.requests[0]
# We should only resume the producer if we're not waiting for the
# transport.
if not self._waitingForTransport:
self._networkProducer.resumeProducing()
if self.persistent:
self._handlingRequest = False
if self._savedTimeOut:
self.setTimeout(self._savedTimeOut)
# Receive our buffered data, if any.
data = b''.join(self._dataBuffer)
self._dataBuffer = []
self.setLineMode(data)
else:
self.loseConnection() | Called by first request in queue when it is done. | requestDone | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def forceAbortClient(self):
"""
Called if C{abortTimeout} seconds have passed since the timeout fired,
and the connection still hasn't gone away. This can really only happen
on extremely bad connections or when clients are maliciously attempting
to keep connections open.
"""
self._log.info(
"Forcibly timing out client: {peer}",
peer=str(self.transport.getPeer())
)
# We want to lose track of the _abortingCall so that no-one tries to
# cancel it.
self._abortingCall = None
self.transport.abortConnection() | Called if C{abortTimeout} seconds have passed since the timeout fired,
and the connection still hasn't gone away. This can really only happen
on extremely bad connections or when clients are maliciously attempting
to keep connections open. | forceAbortClient | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def isSecure(self):
"""
Return L{True} if this channel is using a secure transport.
Normally this method returns L{True} if this instance is using a
transport that implements L{interfaces.ISSLTransport}.
@returns: L{True} if this request is secure
@rtype: C{bool}
"""
if interfaces.ISSLTransport(self.transport, None) is not None:
return True
return False | Return L{True} if this channel is using a secure transport.
Normally this method returns L{True} if this instance is using a
transport that implements L{interfaces.ISSLTransport}.
@returns: L{True} if this request is secure
@rtype: C{bool} | isSecure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def writeHeaders(self, version, code, reason, headers):
"""
Called by L{Request} objects to write a complete set of HTTP headers to
a transport.
@param version: The HTTP version in use.
@type version: L{bytes}
@param code: The HTTP status code to write.
@type code: L{bytes}
@param reason: The HTTP reason phrase to write.
@type reason: L{bytes}
@param headers: The headers to write to the transport.
@type headers: L{twisted.web.http_headers.Headers}
"""
sanitizedHeaders = Headers()
for name, value in headers:
sanitizedHeaders.addRawHeader(name, value)
responseLine = version + b" " + code + b" " + reason + b"\r\n"
headerSequence = [responseLine]
headerSequence.extend(
name + b': ' + value + b"\r\n"
for name, values in sanitizedHeaders.getAllRawHeaders()
for value in values
)
headerSequence.append(b"\r\n")
self.transport.writeSequence(headerSequence) | Called by L{Request} objects to write a complete set of HTTP headers to
a transport.
@param version: The HTTP version in use.
@type version: L{bytes}
@param code: The HTTP status code to write.
@type code: L{bytes}
@param reason: The HTTP reason phrase to write.
@type reason: L{bytes}
@param headers: The headers to write to the transport.
@type headers: L{twisted.web.http_headers.Headers} | writeHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def write(self, data):
"""
Called by L{Request} objects to write response data.
@param data: The data chunk to write to the stream.
@type data: L{bytes}
@return: L{None}
"""
self.transport.write(data) | Called by L{Request} objects to write response data.
@param data: The data chunk to write to the stream.
@type data: L{bytes}
@return: L{None} | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def writeSequence(self, iovec):
"""
Write a list of strings to the HTTP response.
@param iovec: A list of byte strings to write to the stream.
@type data: L{list} of L{bytes}
@return: L{None}
"""
self.transport.writeSequence(iovec) | Write a list of strings to the HTTP response.
@param iovec: A list of byte strings to write to the stream.
@type data: L{list} of L{bytes}
@return: L{None} | writeSequence | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def getPeer(self):
"""
Get the remote address of this connection.
@return: An L{IAddress} provider.
"""
return self.transport.getPeer() | Get the remote address of this connection.
@return: An L{IAddress} provider. | getPeer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def getHost(self):
"""
Get the local address of this connection.
@return: An L{IAddress} provider.
"""
return self.transport.getHost() | Get the local address of this connection.
@return: An L{IAddress} provider. | getHost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def loseConnection(self):
"""
Closes the connection. Will write any data that is pending to be sent
on the network, but if this response has not yet been written to the
network will not write anything.
@return: L{None}
"""
self._networkProducer.unregisterProducer()
return self.transport.loseConnection() | Closes the connection. Will write any data that is pending to be sent
on the network, but if this response has not yet been written to the
network will not write anything.
@return: L{None} | loseConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def registerProducer(self, producer, streaming):
"""
Register to receive data from a producer.
This sets self to be a consumer for a producer. When this object runs
out of data (as when a send(2) call on a socket succeeds in moving the
last data from a userspace buffer into a kernelspace buffer), it will
ask the producer to resumeProducing().
For L{IPullProducer} providers, C{resumeProducing} will be called once
each time data is required.
For L{IPushProducer} providers, C{pauseProducing} will be called
whenever the write buffer fills up and C{resumeProducing} will only be
called when it empties.
@type producer: L{IProducer} provider
@param producer: The L{IProducer} that will be producing data.
@type streaming: L{bool}
@param streaming: C{True} if C{producer} provides L{IPushProducer},
C{False} if C{producer} provides L{IPullProducer}.
@raise RuntimeError: If a producer is already registered.
@return: L{None}
"""
if self._requestProducer is not None:
raise RuntimeError(
"Cannot register producer %s, because producer %s was never "
"unregistered." % (producer, self._requestProducer))
if not streaming:
producer = _PullToPush(producer, self)
self._requestProducer = producer
self._requestProducerStreaming = streaming
if not streaming:
producer.startStreaming() | Register to receive data from a producer.
This sets self to be a consumer for a producer. When this object runs
out of data (as when a send(2) call on a socket succeeds in moving the
last data from a userspace buffer into a kernelspace buffer), it will
ask the producer to resumeProducing().
For L{IPullProducer} providers, C{resumeProducing} will be called once
each time data is required.
For L{IPushProducer} providers, C{pauseProducing} will be called
whenever the write buffer fills up and C{resumeProducing} will only be
called when it empties.
@type producer: L{IProducer} provider
@param producer: The L{IProducer} that will be producing data.
@type streaming: L{bool}
@param streaming: C{True} if C{producer} provides L{IPushProducer},
C{False} if C{producer} provides L{IPullProducer}.
@raise RuntimeError: If a producer is already registered.
@return: L{None} | registerProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def unregisterProducer(self):
"""
Stop consuming data from a producer, without disconnecting.
@return: L{None}
"""
if self._requestProducer is None:
return
if not self._requestProducerStreaming:
self._requestProducer.stopStreaming()
self._requestProducer = None
self._requestProducerStreaming = None | Stop consuming data from a producer, without disconnecting.
@return: L{None} | unregisterProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def stopProducing(self):
"""
Stop producing data.
The HTTPChannel doesn't *actually* implement this, beacuse the
assumption is that it will only be called just before C{loseConnection}
is called. There's nothing sensible we can do other than call
C{loseConnection} anyway.
"""
if self._requestProducer is not None:
self._requestProducer.stopProducing() | Stop producing data.
The HTTPChannel doesn't *actually* implement this, beacuse the
assumption is that it will only be called just before C{loseConnection}
is called. There's nothing sensible we can do other than call
C{loseConnection} anyway. | stopProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def pauseProducing(self):
"""
Pause producing data.
This will be called by the transport when the send buffers have been
filled up. We want to simultaneously pause the producing L{Request}
object and also pause our transport.
The logic behind pausing the transport is specifically to avoid issues
like https://twistedmatrix.com/trac/ticket/8868. In this case, our
inability to send does not prevent us handling more requests, which
means we increasingly queue up more responses in our send buffer
without end. The easiest way to handle this is to ensure that if we are
unable to send our responses, we will not read further data from the
connection until the client pulls some data out. This is a bit of a
blunt instrument, but it's ok.
Note that this potentially interacts with timeout handling in a
positive way. Once the transport is paused the client may run into a
timeout which will cause us to tear the connection down. That's a good
thing!
"""
self._waitingForTransport = True
# The first step is to tell any producer we might currently have
# registered to stop producing. If we can slow our applications down
# we should.
if self._requestProducer is not None:
self._requestProducer.pauseProducing()
# The next step here is to pause our own transport, as discussed in the
# docstring.
if not self._handlingRequest:
self._networkProducer.pauseProducing() | Pause producing data.
This will be called by the transport when the send buffers have been
filled up. We want to simultaneously pause the producing L{Request}
object and also pause our transport.
The logic behind pausing the transport is specifically to avoid issues
like https://twistedmatrix.com/trac/ticket/8868. In this case, our
inability to send does not prevent us handling more requests, which
means we increasingly queue up more responses in our send buffer
without end. The easiest way to handle this is to ensure that if we are
unable to send our responses, we will not read further data from the
connection until the client pulls some data out. This is a bit of a
blunt instrument, but it's ok.
Note that this potentially interacts with timeout handling in a
positive way. Once the transport is paused the client may run into a
timeout which will cause us to tear the connection down. That's a good
thing! | pauseProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def resumeProducing(self):
"""
Resume producing data.
This will be called by the transport when the send buffer has dropped
enough to actually send more data. When this happens we can unpause any
outstanding L{Request} producers we have, and also unpause our
transport.
"""
self._waitingForTransport = False
if self._requestProducer is not None:
self._requestProducer.resumeProducing()
# We only want to resume the network producer if we're not currently
# waiting for a response to show up.
if not self._handlingRequest:
self._networkProducer.resumeProducing() | Resume producing data.
This will be called by the transport when the send buffer has dropped
enough to actually send more data. When this happens we can unpause any
outstanding L{Request} producers we have, and also unpause our
transport. | resumeProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def _send100Continue(self):
"""
Sends a 100 Continue response, used to signal to clients that further
processing will be performed.
"""
self.transport.write(b"HTTP/1.1 100 Continue\r\n\r\n") | Sends a 100 Continue response, used to signal to clients that further
processing will be performed. | _send100Continue | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def _respondToBadRequestAndDisconnect(self):
"""
This is a quick and dirty way of responding to bad requests.
As described by HTTP standard we should be patient and accept the
whole request from the client before sending a polite bad request
response, even in the case when clients send tons of data.
@param transport: Transport handling connection to the client.
@type transport: L{interfaces.ITransport}
"""
self.transport.write(b"HTTP/1.1 400 Bad Request\r\n\r\n")
self.loseConnection() | This is a quick and dirty way of responding to bad requests.
As described by HTTP standard we should be patient and accept the
whole request from the client before sending a polite bad request
response, even in the case when clients send tons of data.
@param transport: Transport handling connection to the client.
@type transport: L{interfaces.ITransport} | _respondToBadRequestAndDisconnect | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def _escape(s):
"""
Return a string like python repr, but always escaped as if surrounding
quotes were double quotes.
@param s: The string to escape.
@type s: L{bytes} or L{unicode}
@return: An escaped string.
@rtype: L{unicode}
"""
if not isinstance(s, bytes):
s = s.encode("ascii")
r = repr(s)
if not isinstance(r, unicode):
r = r.decode("ascii")
if r.startswith(u"b"):
r = r[1:]
if r.startswith(u"'"):
return r[1:-1].replace(u'"', u'\\"').replace(u"\\'", u"'")
return r[1:-1] | Return a string like python repr, but always escaped as if surrounding
quotes were double quotes.
@param s: The string to escape.
@type s: L{bytes} or L{unicode}
@return: An escaped string.
@rtype: L{unicode} | _escape | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def combinedLogFormatter(timestamp, request):
"""
@return: A combined log formatted log line for the given request.
@see: L{IAccessLogFormatter}
"""
clientAddr = request.getClientAddress()
if isinstance(clientAddr, (address.IPv4Address, address.IPv6Address,
_XForwardedForAddress)):
ip = clientAddr.host
else:
ip = b'-'
referrer = _escape(request.getHeader(b"referer") or b"-")
agent = _escape(request.getHeader(b"user-agent") or b"-")
line = (
u'"%(ip)s" - - %(timestamp)s "%(method)s %(uri)s %(protocol)s" '
u'%(code)d %(length)s "%(referrer)s" "%(agent)s"' % dict(
ip=_escape(ip),
timestamp=timestamp,
method=_escape(request.method),
uri=_escape(request.uri),
protocol=_escape(request.clientproto),
code=request.code,
length=request.sentLength or u"-",
referrer=referrer,
agent=agent,
))
return line | @return: A combined log formatted log line for the given request.
@see: L{IAccessLogFormatter} | combinedLogFormatter | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def getClientAddress(self):
"""
The client address (the first address) in the value of the
I{X-Forwarded-For header}. If the header is not present, the IP is
considered to be C{b"-"}.
@return: L{_XForwardedForAddress} which wraps the client address as
expected by L{combinedLogFormatter}.
"""
host = self._request.requestHeaders.getRawHeaders(
b"x-forwarded-for", [b"-"])[0].split(b",")[0].strip()
return _XForwardedForAddress(host) | The client address (the first address) in the value of the
I{X-Forwarded-For header}. If the header is not present, the IP is
considered to be C{b"-"}.
@return: L{_XForwardedForAddress} which wraps the client address as
expected by L{combinedLogFormatter}. | getClientAddress | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def clientproto(self):
"""
@return: The protocol version in the request.
@rtype: L{bytes}
"""
return self._request.clientproto | @return: The protocol version in the request.
@rtype: L{bytes} | clientproto | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def code(self):
"""
@return: The response code for the request.
@rtype: L{int}
"""
return self._request.code | @return: The response code for the request.
@rtype: L{int} | code | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def sentLength(self):
"""
@return: The number of bytes sent in the response body.
@rtype: L{int}
"""
return self._request.sentLength | @return: The number of bytes sent in the response body.
@rtype: L{int} | sentLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def proxiedLogFormatter(timestamp, request):
"""
@return: A combined log formatted log line for the given request but use
the value of the I{X-Forwarded-For} header as the value for the client
IP address.
@see: L{IAccessLogFormatter}
"""
return combinedLogFormatter(timestamp, _XForwardedForRequest(request)) | @return: A combined log formatted log line for the given request but use
the value of the I{X-Forwarded-For} header as the value for the client
IP address.
@see: L{IAccessLogFormatter} | proxiedLogFormatter | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def factory(self):
"""
@see: L{_genericHTTPChannelProtocolFactory}
"""
return self._channel.factory | @see: L{_genericHTTPChannelProtocolFactory} | factory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def requestFactory(self):
"""
A callable to use to build L{IRequest} objects.
Retries the object from the current backing channel.
"""
return self._channel.requestFactory | A callable to use to build L{IRequest} objects.
Retries the object from the current backing channel. | requestFactory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def requestFactory(self, value):
"""
A callable to use to build L{IRequest} objects.
Sets the object on the backing channel and also stores the value for
propagation to any new channel.
@param value: The new callable to use.
@type value: A L{callable} returning L{IRequest}
"""
self._requestFactory = value
self._channel.requestFactory = value | A callable to use to build L{IRequest} objects.
Sets the object on the backing channel and also stores the value for
propagation to any new channel.
@param value: The new callable to use.
@type value: A L{callable} returning L{IRequest} | requestFactory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def site(self):
"""
A reference to the creating L{twisted.web.server.Site} object.
Returns the site object from the backing channel.
"""
return self._channel.site | A reference to the creating L{twisted.web.server.Site} object.
Returns the site object from the backing channel. | site | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def site(self, value):
"""
A reference to the creating L{twisted.web.server.Site} object.
Sets the object on the backing channel and also stores the value for
propagation to any new channel.
@param value: The L{twisted.web.server.Site} object to set.
@type value: L{twisted.web.server.Site}
"""
self._site = value
self._channel.site = value | A reference to the creating L{twisted.web.server.Site} object.
Sets the object on the backing channel and also stores the value for
propagation to any new channel.
@param value: The L{twisted.web.server.Site} object to set.
@type value: L{twisted.web.server.Site} | site | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def timeOut(self):
"""
The idle timeout for the backing channel.
"""
return self._channel.timeOut | The idle timeout for the backing channel. | timeOut | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def timeOut(self, value):
"""
The idle timeout for the backing channel.
Sets the idle timeout on both the backing channel and stores it for
propagation to any new backing channel.
@param value: The timeout to set.
@type value: L{int} or L{float}
"""
self._timeOut = value
self._channel.timeOut = value | The idle timeout for the backing channel.
Sets the idle timeout on both the backing channel and stores it for
propagation to any new backing channel.
@param value: The timeout to set.
@type value: L{int} or L{float} | timeOut | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def callLater(self):
"""
A value for the C{callLater} callback. This callback is used by the
L{twisted.protocols.policies.TimeoutMixin} to handle timeouts.
"""
return self._channel.callLater | A value for the C{callLater} callback. This callback is used by the
L{twisted.protocols.policies.TimeoutMixin} to handle timeouts. | callLater | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def callLater(self, value):
"""
Sets the value for the C{callLater} callback. This callback is used by
the L{twisted.protocols.policies.TimeoutMixin} to handle timeouts.
@param value: The new callback to use.
@type value: L{callable}
"""
self._callLater = value
self._channel.callLater = value | Sets the value for the C{callLater} callback. This callback is used by
the L{twisted.protocols.policies.TimeoutMixin} to handle timeouts.
@param value: The new callback to use.
@type value: L{callable} | callLater | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def dataReceived(self, data):
"""
An override of L{IProtocol.dataReceived} that checks what protocol we're
using.
"""
if self._negotiatedProtocol is None:
try:
negotiatedProtocol = self._channel.transport.negotiatedProtocol
except AttributeError:
# Plaintext HTTP, always HTTP/1.1
negotiatedProtocol = b'http/1.1'
if negotiatedProtocol is None:
negotiatedProtocol = b'http/1.1'
if negotiatedProtocol == b'h2':
if not H2_ENABLED:
raise ValueError("Negotiated HTTP/2 without support.")
# We need to make sure that the HTTPChannel is unregistered
# from the transport so that the H2Connection can register
# itself if possible.
self._channel._networkProducer.unregisterProducer()
transport = self._channel.transport
self._channel = H2Connection()
self._channel.requestFactory = self._requestFactory
self._channel.site = self._site
self._channel.factory = self._factory
self._channel.timeOut = self._timeOut
self._channel.callLater = self._callLater
self._channel.makeConnection(transport)
else:
# Only HTTP/2 and HTTP/1.1 are supported right now.
assert negotiatedProtocol == b'http/1.1', \
"Unsupported protocol negotiated"
self._negotiatedProtocol = negotiatedProtocol
return self._channel.dataReceived(data) | An override of L{IProtocol.dataReceived} that checks what protocol we're
using. | dataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def _genericHTTPChannelProtocolFactory(self):
"""
Returns an appropriately initialized _GenericHTTPChannelProtocol.
"""
return _GenericHTTPChannelProtocol(HTTPChannel()) | Returns an appropriately initialized _GenericHTTPChannelProtocol. | _genericHTTPChannelProtocolFactory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def __init__(self, logPath=None, timeout=_REQUEST_TIMEOUT,
logFormatter=None, reactor=None):
"""
@param logPath: File path to which access log messages will be written
or C{None} to disable logging.
@type logPath: L{str} or L{bytes}
@param timeout: The initial value of L{timeOut}, which defines the idle
connection timeout in seconds, or C{None} to disable the idle
timeout.
@type timeout: L{float}
@param logFormatter: An object to format requests into log lines for
the access log. L{combinedLogFormatter} when C{None} is passed.
@type logFormatter: L{IAccessLogFormatter} provider
@param reactor: A L{IReactorTime} provider used to manage connection
timeouts and compute logging timestamps.
"""
if not reactor:
from twisted.internet import reactor
self._reactor = reactor
if logPath is not None:
logPath = os.path.abspath(logPath)
self.logPath = logPath
self.timeOut = timeout
if logFormatter is None:
logFormatter = combinedLogFormatter
self._logFormatter = logFormatter
# For storing the cached log datetime and the callback to update it
self._logDateTime = None
self._logDateTimeCall = None | @param logPath: File path to which access log messages will be written
or C{None} to disable logging.
@type logPath: L{str} or L{bytes}
@param timeout: The initial value of L{timeOut}, which defines the idle
connection timeout in seconds, or C{None} to disable the idle
timeout.
@type timeout: L{float}
@param logFormatter: An object to format requests into log lines for
the access log. L{combinedLogFormatter} when C{None} is passed.
@type logFormatter: L{IAccessLogFormatter} provider
@param reactor: A L{IReactorTime} provider used to manage connection
timeouts and compute logging timestamps. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def _updateLogDateTime(self):
"""
Update log datetime periodically, so we aren't always recalculating it.
"""
self._logDateTime = datetimeToLogString(self._reactor.seconds())
self._logDateTimeCall = self._reactor.callLater(1, self._updateLogDateTime) | Update log datetime periodically, so we aren't always recalculating it. | _updateLogDateTime | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def startFactory(self):
"""
Set up request logging if necessary.
"""
if self._logDateTimeCall is None:
self._updateLogDateTime()
if self.logPath:
self.logFile = self._openLogFile(self.logPath)
else:
self.logFile = log.logfile | Set up request logging if necessary. | startFactory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def _openLogFile(self, path):
"""
Override in subclasses, e.g. to use L{twisted.python.logfile}.
"""
f = open(path, "ab", 1)
return f | Override in subclasses, e.g. to use L{twisted.python.logfile}. | _openLogFile | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def log(self, request):
"""
Write a line representing C{request} to the access log file.
@param request: The request object about which to log.
@type request: L{Request}
"""
try:
logFile = self.logFile
except AttributeError:
pass
else:
line = self._logFormatter(self._logDateTime, request) + u"\n"
logFile.write(line.encode('utf8')) | Write a line representing C{request} to the access log file.
@param request: The request object about which to log.
@type request: L{Request} | log | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py | MIT |
def handleResponseEnd(self):
"""
Finish the original request, indicating that the response has been
completely written to it, and disconnect the outgoing transport.
"""
if not self._finished:
self._finished = True
self.father.finish()
self.transport.loseConnection() | Finish the original request, indicating that the response has been
completely written to it, and disconnect the outgoing transport. | handleResponseEnd | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | MIT |
def clientConnectionFailed(self, connector, reason):
"""
Report a connection failure in a response to the incoming request as
an error.
"""
self.father.setResponseCode(501, b"Gateway error")
self.father.responseHeaders.addRawHeader(b"Content-Type", b"text/html")
self.father.write(b"<H1>Could not connect</H1>")
self.father.finish() | Report a connection failure in a response to the incoming request as
an error. | clientConnectionFailed | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | MIT |
def process(self):
"""
Handle this request by connecting to the proxied server and forwarding
it there, then forwarding the response back as the response to this
request.
"""
self.requestHeaders.setRawHeaders(b"host",
[self.factory.host.encode('ascii')])
clientFactory = self.proxyClientFactoryClass(
self.method, self.uri, self.clientproto, self.getAllHeaders(),
self.content.read(), self)
self.reactor.connectTCP(self.factory.host, self.factory.port,
clientFactory) | Handle this request by connecting to the proxied server and forwarding
it there, then forwarding the response back as the response to this
request. | process | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | MIT |
def __init__(self, host, port, path, reactor=reactor):
"""
@param host: the host of the web server to proxy.
@type host: C{str}
@param port: the port of the web server to proxy.
@type port: C{port}
@param path: the base path to fetch data from. Note that you shouldn't
put any trailing slashes in it, it will be added automatically in
request. For example, if you put B{/foo}, a request on B{/bar} will
be proxied to B{/foo/bar}. Any required encoding of special
characters (such as " " or "/") should have been done already.
@type path: C{bytes}
"""
Resource.__init__(self)
self.host = host
self.port = port
self.path = path
self.reactor = reactor | @param host: the host of the web server to proxy.
@type host: C{str}
@param port: the port of the web server to proxy.
@type port: C{port}
@param path: the base path to fetch data from. Note that you shouldn't
put any trailing slashes in it, it will be added automatically in
request. For example, if you put B{/foo}, a request on B{/bar} will
be proxied to B{/foo/bar}. Any required encoding of special
characters (such as " " or "/") should have been done already.
@type path: C{bytes} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | MIT |
def getChild(self, path, request):
"""
Create and return a proxy resource with the same proxy configuration
as this one, except that its path also contains the segment given by
C{path} at the end.
"""
return ReverseProxyResource(
self.host, self.port, self.path + b'/' + urlquote(path, safe=b"").encode('utf-8'),
self.reactor) | Create and return a proxy resource with the same proxy configuration
as this one, except that its path also contains the segment given by
C{path} at the end. | getChild | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | MIT |
def render(self, request):
"""
Render a request by forwarding it to the proxied server.
"""
# RFC 2616 tells us that we can omit the port if it's the default port,
# but we have to provide it otherwise
if self.port == 80:
host = self.host
else:
host = u"%s:%d" % (self.host, self.port)
request.requestHeaders.setRawHeaders(b"host", [host.encode('ascii')])
request.content.seek(0, 0)
qs = urllib_parse.urlparse(request.uri)[4]
if qs:
rest = self.path + b'?' + qs
else:
rest = self.path
clientFactory = self.proxyClientFactoryClass(
request.method, rest, request.clientproto,
request.getAllHeaders(), request.content.read(), request)
self.reactor.connectTCP(self.host, self.port, clientFactory)
return NOT_DONE_YET | Render a request by forwarding it to the proxied server. | render | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py | MIT |
def __init__(self, filename, registry=None, reactor=None):
"""
Initialize, with the name of a CGI script file.
"""
self.filename = filename
if reactor is None:
# This installs a default reactor, if None was installed before.
# We do a late import here, so that importing the current module
# won't directly trigger installing a default reactor.
from twisted.internet import reactor
self._reactor = reactor | Initialize, with the name of a CGI script file. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py | MIT |
def render(self, request):
"""
Do various things to conform to the CGI specification.
I will set up the usual slew of environment variables, then spin off a
process.
@type request: L{twisted.web.http.Request}
@param request: An HTTP request.
"""
scriptName = b"/" + b"/".join(request.prepath)
serverName = request.getRequestHostname().split(b':')[0]
env = {"SERVER_SOFTWARE": server.version,
"SERVER_NAME": serverName,
"GATEWAY_INTERFACE": "CGI/1.1",
"SERVER_PROTOCOL": request.clientproto,
"SERVER_PORT": str(request.getHost().port),
"REQUEST_METHOD": request.method,
"SCRIPT_NAME": scriptName,
"SCRIPT_FILENAME": self.filename,
"REQUEST_URI": request.uri}
ip = request.getClientAddress().host
if ip is not None:
env['REMOTE_ADDR'] = ip
pp = request.postpath
if pp:
env["PATH_INFO"] = "/" + "/".join(pp)
if hasattr(request, "content"):
# 'request.content' is either a StringIO or a TemporaryFile, and
# the file pointer is sitting at the beginning (seek(0,0))
request.content.seek(0, 2)
length = request.content.tell()
request.content.seek(0, 0)
env['CONTENT_LENGTH'] = str(length)
try:
qindex = request.uri.index(b'?')
except ValueError:
env['QUERY_STRING'] = ''
qargs = []
else:
qs = env['QUERY_STRING'] = request.uri[qindex+1:]
if '=' in qs:
qargs = []
else:
qargs = [urllib.unquote(x) for x in qs.split('+')]
# Propagate HTTP headers
for title, header in request.getAllHeaders().items():
envname = title.replace(b'-', b'_').upper()
if title not in (b'content-type', b'content-length', b'proxy'):
envname = b"HTTP_" + envname
env[envname] = header
# Propagate our environment
for key, value in os.environ.items():
if key not in env:
env[key] = value
# And they're off!
self.runProcess(env, request, qargs)
return server.NOT_DONE_YET | Do various things to conform to the CGI specification.
I will set up the usual slew of environment variables, then spin off a
process.
@type request: L{twisted.web.http.Request}
@param request: An HTTP request. | render | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py | MIT |
def runProcess(self, env, request, qargs=[]):
"""
Run the cgi script.
@type env: A L{dict} of L{str}, or L{None}
@param env: The environment variables to pass to the process that will
get spawned. See
L{twisted.internet.interfaces.IReactorProcess.spawnProcess} for
more information about environments and process creation.
@type request: L{twisted.web.http.Request}
@param request: An HTTP request.
@type qargs: A L{list} of L{str}
@param qargs: The command line arguments to pass to the process that
will get spawned.
"""
p = CGIProcessProtocol(request)
self._reactor.spawnProcess(p, self.filename, [self.filename] + qargs,
env, os.path.dirname(self.filename)) | Run the cgi script.
@type env: A L{dict} of L{str}, or L{None}
@param env: The environment variables to pass to the process that will
get spawned. See
L{twisted.internet.interfaces.IReactorProcess.spawnProcess} for
more information about environments and process creation.
@type request: L{twisted.web.http.Request}
@param request: An HTTP request.
@type qargs: A L{list} of L{str}
@param qargs: The command line arguments to pass to the process that
will get spawned. | runProcess | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py | MIT |
def runProcess(self, env, request, qargs=[]):
"""
Run a script through the C{filter} executable.
@type env: A L{dict} of L{str}, or L{None}
@param env: The environment variables to pass to the process that will
get spawned. See
L{twisted.internet.interfaces.IReactorProcess.spawnProcess}
for more information about environments and process creation.
@type request: L{twisted.web.http.Request}
@param request: An HTTP request.
@type qargs: A L{list} of L{str}
@param qargs: The command line arguments to pass to the process that
will get spawned.
"""
p = CGIProcessProtocol(request)
self._reactor.spawnProcess(p, self.filter,
[self.filter, self.filename] + qargs, env,
os.path.dirname(self.filename)) | Run a script through the C{filter} executable.
@type env: A L{dict} of L{str}, or L{None}
@param env: The environment variables to pass to the process that will
get spawned. See
L{twisted.internet.interfaces.IReactorProcess.spawnProcess}
for more information about environments and process creation.
@type request: L{twisted.web.http.Request}
@param request: An HTTP request.
@type qargs: A L{list} of L{str}
@param qargs: The command line arguments to pass to the process that
will get spawned. | runProcess | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py | MIT |
def outReceived(self, output):
"""
Handle a chunk of input
"""
# First, make sure that the headers from the script are sorted
# out (we'll want to do some parsing on these later.)
if self.handling_headers:
text = self.headertext + output
headerEnds = []
for delimiter in b'\n\n', b'\r\n\r\n', b'\r\r', b'\n\r\n':
headerend = text.find(delimiter)
if headerend != -1:
headerEnds.append((headerend, delimiter))
if headerEnds:
# The script is entirely in control of response headers;
# disable the default Content-Type value normally provided by
# twisted.web.server.Request.
self.request.defaultContentType = None
headerEnds.sort()
headerend, delimiter = headerEnds[0]
self.headertext = text[:headerend]
# This is a final version of the header text.
linebreak = delimiter[:len(delimiter)//2]
headers = self.headertext.split(linebreak)
for header in headers:
br = header.find(b': ')
if br == -1:
self._log.error(
'ignoring malformed CGI header: {header!r}',
header=header)
else:
headerName = header[:br].lower()
headerText = header[br+2:]
if headerName == b'location':
self.request.setResponseCode(http.FOUND)
if headerName == b'status':
try:
# "XXX <description>" sometimes happens.
statusNum = int(headerText[:3])
except:
self._log.error("malformed status header")
else:
self.request.setResponseCode(statusNum)
else:
# Don't allow the application to control
# these required headers.
if headerName.lower() not in (b'server', b'date'):
self.request.responseHeaders.addRawHeader(
headerName, headerText)
output = text[headerend+len(delimiter):]
self.handling_headers = 0
if self.handling_headers:
self.headertext = text
if not self.handling_headers:
self.request.write(output) | Handle a chunk of input | outReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py | MIT |
def withRequest(f):
"""
Decorator to cause the request to be passed as the first argument
to the method.
If an I{xmlrpc_} method is wrapped with C{withRequest}, the
request object is passed as the first argument to that method.
For example::
@withRequest
def xmlrpc_echo(self, request, s):
return s
@since: 10.2
"""
f.withRequest = True
return f | Decorator to cause the request to be passed as the first argument
to the method.
If an I{xmlrpc_} method is wrapped with C{withRequest}, the
request object is passed as the first argument to that method.
For example::
@withRequest
def xmlrpc_echo(self, request, s):
return s
@since: 10.2 | withRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def lookupProcedure(self, procedurePath):
"""
Given a string naming a procedure, return a callable object for that
procedure or raise NoSuchFunction.
The returned object will be called, and should return the result of the
procedure, a Deferred, or a Fault instance.
Override in subclasses if you want your own policy. The base
implementation that given C{'foo'}, C{self.xmlrpc_foo} will be returned.
If C{procedurePath} contains C{self.separator}, the sub-handler for the
initial prefix is used to search for the remaining path.
If you override C{lookupProcedure}, you may also want to override
C{listProcedures} to accurately report the procedures supported by your
resource, so that clients using the I{system.listMethods} procedure
receive accurate results.
@since: 11.1
"""
if procedurePath.find(self.separator) != -1:
prefix, procedurePath = procedurePath.split(self.separator, 1)
handler = self.getSubHandler(prefix)
if handler is None:
raise NoSuchFunction(self.NOT_FOUND,
"no such subHandler %s" % prefix)
return handler.lookupProcedure(procedurePath)
f = getattr(self, "xmlrpc_%s" % procedurePath, None)
if not f:
raise NoSuchFunction(self.NOT_FOUND,
"procedure %s not found" % procedurePath)
elif not callable(f):
raise NoSuchFunction(self.NOT_FOUND,
"procedure %s not callable" % procedurePath)
else:
return f | Given a string naming a procedure, return a callable object for that
procedure or raise NoSuchFunction.
The returned object will be called, and should return the result of the
procedure, a Deferred, or a Fault instance.
Override in subclasses if you want your own policy. The base
implementation that given C{'foo'}, C{self.xmlrpc_foo} will be returned.
If C{procedurePath} contains C{self.separator}, the sub-handler for the
initial prefix is used to search for the remaining path.
If you override C{lookupProcedure}, you may also want to override
C{listProcedures} to accurately report the procedures supported by your
resource, so that clients using the I{system.listMethods} procedure
receive accurate results.
@since: 11.1 | lookupProcedure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def listProcedures(self):
"""
Return a list of the names of all xmlrpc procedures.
@since: 11.1
"""
return reflect.prefixedMethodNames(self.__class__, 'xmlrpc_') | Return a list of the names of all xmlrpc procedures.
@since: 11.1 | listProcedures | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def __init__(self, parent):
"""
Implement Introspection support for an XMLRPC server.
@param parent: the XMLRPC server to add Introspection support to.
@type parent: L{XMLRPC}
"""
XMLRPC.__init__(self)
self._xmlrpc_parent = parent | Implement Introspection support for an XMLRPC server.
@param parent: the XMLRPC server to add Introspection support to.
@type parent: L{XMLRPC} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def xmlrpc_listMethods(self):
"""
Return a list of the method names implemented by this server.
"""
functions = []
todo = [(self._xmlrpc_parent, '')]
while todo:
obj, prefix = todo.pop(0)
functions.extend([prefix + name for name in obj.listProcedures()])
todo.extend([ (obj.getSubHandler(name),
prefix + name + obj.separator)
for name in obj.getSubHandlerPrefixes() ])
return functions | Return a list of the method names implemented by this server. | xmlrpc_listMethods | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def xmlrpc_methodHelp(self, method):
"""
Return a documentation string describing the use of the given method.
"""
method = self._xmlrpc_parent.lookupProcedure(method)
return (getattr(method, 'help', None)
or getattr(method, '__doc__', None) or '') | Return a documentation string describing the use of the given method. | xmlrpc_methodHelp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def xmlrpc_methodSignature(self, method):
"""
Return a list of type signatures.
Each type signature is a list of the form [rtype, type1, type2, ...]
where rtype is the return type and typeN is the type of the Nth
argument. If no signature information is available, the empty
string is returned.
"""
method = self._xmlrpc_parent.lookupProcedure(method)
return getattr(method, 'signature', None) or '' | Return a list of type signatures.
Each type signature is a list of the form [rtype, type1, type2, ...]
where rtype is the return type and typeN is the type of the Nth
argument. If no signature information is available, the empty
string is returned. | xmlrpc_methodSignature | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def addIntrospection(xmlrpc):
"""
Add Introspection support to an XMLRPC server.
@param parent: the XMLRPC server to add Introspection support to.
@type parent: L{XMLRPC}
"""
xmlrpc.putSubHandler('system', XMLRPCIntrospection(xmlrpc)) | Add Introspection support to an XMLRPC server.
@param parent: the XMLRPC server to add Introspection support to.
@type parent: L{XMLRPC} | addIntrospection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def handleResponse(self, contents):
"""
Handle the XML-RPC response received from the server.
Specifically, disconnect from the server and store the XML-RPC
response so that it can be properly handled when the disconnect is
finished.
"""
self.transport.loseConnection()
self._response = contents | Handle the XML-RPC response received from the server.
Specifically, disconnect from the server and store the XML-RPC
response so that it can be properly handled when the disconnect is
finished. | handleResponse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def connectionLost(self, reason):
"""
The connection to the server has been lost.
If we have a full response from the server, then parse it and fired a
Deferred with the return value or C{Fault} that the server gave us.
"""
http.HTTPClient.connectionLost(self, reason)
if self._response is not None:
response, self._response = self._response, None
self.factory.parseResponse(response) | The connection to the server has been lost.
If we have a full response from the server, then parse it and fired a
Deferred with the return value or C{Fault} that the server gave us. | connectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def __init__(self, path, host, method, user=None, password=None,
allowNone=False, args=(), canceller=None, useDateTime=False):
"""
@param method: The name of the method to call.
@type method: C{str}
@param allowNone: allow the use of None values in parameters. It's
passed to the underlying xmlrpclib implementation. Defaults to
C{False}.
@type allowNone: C{bool} or L{None}
@param args: the arguments to pass to the method.
@type args: C{tuple}
@param canceller: A 1-argument callable passed to the deferred as the
canceller callback.
@type canceller: callable or L{None}
"""
self.path, self.host = path, host
self.user, self.password = user, password
self.payload = payloadTemplate % (method,
xmlrpclib.dumps(args, allow_none=allowNone))
if isinstance(self.payload, unicode):
self.payload = self.payload.encode('utf8')
self.deferred = defer.Deferred(canceller)
self.useDateTime = useDateTime | @param method: The name of the method to call.
@type method: C{str}
@param allowNone: allow the use of None values in parameters. It's
passed to the underlying xmlrpclib implementation. Defaults to
C{False}.
@type allowNone: C{bool} or L{None}
@param args: the arguments to pass to the method.
@type args: C{tuple}
@param canceller: A 1-argument callable passed to the deferred as the
canceller callback.
@type canceller: callable or L{None} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def __init__(self, url, user=None, password=None, allowNone=False,
useDateTime=False, connectTimeout=30.0, reactor=reactor):
"""
@param url: The URL to which to post method calls. Calls will be made
over SSL if the scheme is HTTPS. If netloc contains username or
password information, these will be used to authenticate, as long as
the C{user} and C{password} arguments are not specified.
@type url: L{bytes}
"""
scheme, netloc, path, params, query, fragment = urllib_parse.urlparse(
url)
netlocParts = netloc.split(b'@')
if len(netlocParts) == 2:
userpass = netlocParts.pop(0).split(b':')
self.user = userpass.pop(0)
try:
self.password = userpass.pop(0)
except:
self.password = None
else:
self.user = self.password = None
hostport = netlocParts[0].split(b':')
self.host = hostport.pop(0)
try:
self.port = int(hostport.pop(0))
except:
self.port = None
self.path = path
if self.path in [b'', None]:
self.path = b'/'
self.secure = (scheme == b'https')
if user is not None:
self.user = user
if password is not None:
self.password = password
self.allowNone = allowNone
self.useDateTime = useDateTime
self.connectTimeout = connectTimeout
self._reactor = reactor | @param url: The URL to which to post method calls. Calls will be made
over SSL if the scheme is HTTPS. If netloc contains username or
password information, these will be used to authenticate, as long as
the C{user} and C{password} arguments are not specified.
@type url: L{bytes} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def callRemote(self, method, *args):
"""
Call remote XML-RPC C{method} with given arguments.
@return: a L{defer.Deferred} that will fire with the method response,
or a failure if the method failed. Generally, the failure type will
be L{Fault}, but you can also have an C{IndexError} on some buggy
servers giving empty responses.
If the deferred is cancelled before the request completes, the
connection is closed and the deferred will fire with a
L{defer.CancelledError}.
"""
def cancel(d):
factory.deferred = None
connector.disconnect()
factory = self.queryFactory(
self.path, self.host, method, self.user,
self.password, self.allowNone, args, cancel, self.useDateTime)
if self.secure:
from twisted.internet import ssl
connector = self._reactor.connectSSL(
nativeString(self.host), self.port or 443,
factory, ssl.ClientContextFactory(),
timeout=self.connectTimeout)
else:
connector = self._reactor.connectTCP(
nativeString(self.host), self.port or 80, factory,
timeout=self.connectTimeout)
return factory.deferred | Call remote XML-RPC C{method} with given arguments.
@return: a L{defer.Deferred} that will fire with the method response,
or a failure if the method failed. Generally, the failure type will
be L{Fault}, but you can also have an C{IndexError} on some buggy
servers giving empty responses.
If the deferred is cancelled before the request completes, the
connection is closed and the deferred will fire with a
L{defer.CancelledError}. | callRemote | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py | MIT |
def _PRE(text):
"""
Wraps <pre> tags around some text and HTML-escape it.
This is here since once twisted.web.html was deprecated it was hard to
migrate the html.PRE from current code to twisted.web.template.
For new code consider using twisted.web.template.
@return: Escaped text wrapped in <pre> tags.
@rtype: C{str}
"""
return '<pre>%s</pre>' % (escape(text),) | Wraps <pre> tags around some text and HTML-escape it.
This is here since once twisted.web.html was deprecated it was hard to
migrate the html.PRE from current code to twisted.web.template.
For new code consider using twisted.web.template.
@return: Escaped text wrapped in <pre> tags.
@rtype: C{str} | _PRE | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def redirectTo(URL, request):
"""
Generate a redirect to the given location.
@param URL: A L{bytes} giving the location to which to redirect.
@type URL: L{bytes}
@param request: The request object to use to generate the redirect.
@type request: L{IRequest<twisted.web.iweb.IRequest>} provider
@raise TypeError: If the type of C{URL} a L{unicode} instead of L{bytes}.
@return: A C{bytes} containing HTML which tries to convince the client agent
to visit the new location even if it doesn't respect the I{FOUND}
response code. This is intended to be returned from a render method,
eg::
def render_GET(self, request):
return redirectTo(b"http://example.com/", request)
"""
if isinstance(URL, unicode) :
raise TypeError("Unicode object not allowed as URL")
request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
request.redirect(URL)
content = """
<html>
<head>
<meta http-equiv=\"refresh\" content=\"0;URL=%(url)s\">
</head>
<body bgcolor=\"#FFFFFF\" text=\"#000000\">
<a href=\"%(url)s\">click here</a>
</body>
</html>
""" % {'url': nativeString(URL)}
if _PY3:
content = content.encode("utf8")
return content | Generate a redirect to the given location.
@param URL: A L{bytes} giving the location to which to redirect.
@type URL: L{bytes}
@param request: The request object to use to generate the redirect.
@type request: L{IRequest<twisted.web.iweb.IRequest>} provider
@raise TypeError: If the type of C{URL} a L{unicode} instead of L{bytes}.
@return: A C{bytes} containing HTML which tries to convince the client agent
to visit the new location even if it doesn't respect the I{FOUND}
response code. This is intended to be returned from a render method,
eg::
def render_GET(self, request):
return redirectTo(b"http://example.com/", request) | redirectTo | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def sourceLine(self, request, tag):
"""
Render the line of source as a child of C{tag}.
"""
return tag(self.source.replace(' ', u' \N{NO-BREAK SPACE}')) | Render the line of source as a child of C{tag}. | sourceLine | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def lineNumber(self, request, tag):
"""
Render the line number as a child of C{tag}.
"""
return tag(str(self.number)) | Render the line number as a child of C{tag}. | lineNumber | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def _getSourceLines(self):
"""
Find the source line references by C{self.frame} and yield, in source
line order, it and the previous and following lines.
@return: A generator which yields two-tuples. Each tuple gives a source
line number and the contents of that source line.
"""
filename = self.frame[1]
lineNumber = self.frame[2]
for snipLineNumber in range(lineNumber - 1, lineNumber + 2):
yield (snipLineNumber,
linecache.getline(filename, snipLineNumber).rstrip()) | Find the source line references by C{self.frame} and yield, in source
line order, it and the previous and following lines.
@return: A generator which yields two-tuples. Each tuple gives a source
line number and the contents of that source line. | _getSourceLines | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def sourceLines(self, request, tag):
"""
Render the source line indicated by C{self.frame} and several
surrounding lines. The active line will be given a I{class} of
C{"snippetHighlightLine"}. Other lines will be given a I{class} of
C{"snippetLine"}.
"""
for (lineNumber, sourceLine) in self._getSourceLines():
newTag = tag.clone()
if lineNumber == self.frame[2]:
cssClass = "snippetHighlightLine"
else:
cssClass = "snippetLine"
loader = TagLoader(newTag(**{"class": cssClass}))
yield _SourceLineElement(loader, lineNumber, sourceLine) | Render the source line indicated by C{self.frame} and several
surrounding lines. The active line will be given a I{class} of
C{"snippetHighlightLine"}. Other lines will be given a I{class} of
C{"snippetLine"}. | sourceLines | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def filename(self, request, tag):
"""
Render the name of the file this frame references as a child of C{tag}.
"""
return tag(self.frame[1]) | Render the name of the file this frame references as a child of C{tag}. | filename | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def lineNumber(self, request, tag):
"""
Render the source line number this frame references as a child of
C{tag}.
"""
return tag(str(self.frame[2])) | Render the source line number this frame references as a child of
C{tag}. | lineNumber | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def function(self, request, tag):
"""
Render the function name this frame references as a child of C{tag}.
"""
return tag(self.frame[0]) | Render the function name this frame references as a child of C{tag}. | function | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def source(self, request, tag):
"""
Render the source code surrounding the line this frame references,
replacing C{tag}.
"""
return _SourceFragmentElement(TagLoader(tag), self.frame) | Render the source code surrounding the line this frame references,
replacing C{tag}. | source | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def frames(self, request, tag):
"""
Render the list of frames in this L{_StackElement}, replacing C{tag}.
"""
return [
_FrameElement(TagLoader(tag.clone()), frame)
for frame
in self.stackFrames] | Render the list of frames in this L{_StackElement}, replacing C{tag}. | frames | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def type(self, request, tag):
"""
Render the exception type as a child of C{tag}.
"""
return tag(fullyQualifiedName(self.failure.type)) | Render the exception type as a child of C{tag}. | type | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def value(self, request, tag):
"""
Render the exception value as a child of C{tag}.
"""
return tag(unicode(self.failure.value).encode('utf8')) | Render the exception value as a child of C{tag}. | value | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def traceback(self, request, tag):
"""
Render all the frames in the wrapped
L{Failure<twisted.python.failure.Failure>}'s traceback stack, replacing
C{tag}.
"""
return _StackElement(TagLoader(tag), self.failure.frames) | Render all the frames in the wrapped
L{Failure<twisted.python.failure.Failure>}'s traceback stack, replacing
C{tag}. | traceback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def formatFailure(myFailure):
"""
Construct an HTML representation of the given failure.
Consider using L{FailureElement} instead.
@type myFailure: L{Failure<twisted.python.failure.Failure>}
@rtype: C{bytes}
@return: A string containing the HTML representation of the given failure.
"""
result = []
flattenString(None, FailureElement(myFailure)).addBoth(result.append)
if isinstance(result[0], bytes):
# Ensure the result string is all ASCII, for compatibility with the
# default encoding expected by browsers.
return result[0].decode('utf-8').encode('ascii', 'xmlcharrefreplace')
result[0].raiseException() | Construct an HTML representation of the given failure.
Consider using L{FailureElement} instead.
@type myFailure: L{Failure<twisted.python.failure.Failure>}
@rtype: C{bytes}
@return: A string containing the HTML representation of the given failure. | formatFailure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py | MIT |
def alias(aliasPath, sourcePath):
"""
I am not a very good aliaser. But I'm the best I can be. If I'm
aliasing to a Resource that generates links, and it uses any parts
of request.prepath to do so, the links will not be relative to the
aliased path, but rather to the aliased-to path. That I can't
alias static.File directory listings that nicely. However, I can
still be useful, as many resources will play nice.
"""
sourcePath = sourcePath.split('/')
aliasPath = aliasPath.split('/')
def rewriter(request):
if request.postpath[:len(aliasPath)] == aliasPath:
after = request.postpath[len(aliasPath):]
request.postpath = sourcePath + after
request.path = '/'+'/'.join(request.prepath+request.postpath)
return rewriter | I am not a very good aliaser. But I'm the best I can be. If I'm
aliasing to a Resource that generates links, and it uses any parts
of request.prepath to do so, the links will not be relative to the
aliased path, but rather to the aliased-to path. That I can't
alias static.File directory listings that nicely. However, I can
still be useful, as many resources will play nice. | alias | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/rewrite.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/rewrite.py | MIT |
def getElementsByTagName(iNode, name):
"""
Return a list of all child elements of C{iNode} with a name matching
C{name}.
Note that this implementation does not conform to the DOM Level 1 Core
specification because it may return C{iNode}.
@param iNode: An element at which to begin searching. If C{iNode} has a
name matching C{name}, it will be included in the result.
@param name: A C{str} giving the name of the elements to return.
@return: A C{list} of direct or indirect child elements of C{iNode} with
the name C{name}. This may include C{iNode}.
"""
matches = []
matches_append = matches.append # faster lookup. don't do this at home
slice = [iNode]
while len(slice) > 0:
c = slice.pop(0)
if c.nodeName == name:
matches_append(c)
slice[:0] = c.childNodes
return matches | Return a list of all child elements of C{iNode} with a name matching
C{name}.
Note that this implementation does not conform to the DOM Level 1 Core
specification because it may return C{iNode}.
@param iNode: An element at which to begin searching. If C{iNode} has a
name matching C{name}, it will be included in the result.
@param name: A C{str} giving the name of the elements to return.
@return: A C{list} of direct or indirect child elements of C{iNode} with
the name C{name}. This may include C{iNode}. | getElementsByTagName | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def unescape(text, chars=REV_HTML_ESCAPE_CHARS):
"""
Perform the exact opposite of 'escape'.
"""
for s, h in chars:
text = text.replace(h, s)
return text | Perform the exact opposite of 'escape'. | unescape | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def escape(text, chars=HTML_ESCAPE_CHARS):
"""
Escape a few XML special chars with XML entities.
"""
for s, h in chars:
text = text.replace(s, h)
return text | Escape a few XML special chars with XML entities. | escape | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def isEqualToNode(self, other):
"""
Compare this node to C{other}. If the nodes have the same number of
children and corresponding children are equal to each other, return
C{True}, otherwise return C{False}.
@type other: L{Node}
@rtype: C{bool}
"""
if len(self.childNodes) != len(other.childNodes):
return False
for a, b in zip(self.childNodes, other.childNodes):
if not a.isEqualToNode(b):
return False
return True | Compare this node to C{other}. If the nodes have the same number of
children and corresponding children are equal to each other, return
C{True}, otherwise return C{False}.
@type other: L{Node}
@rtype: C{bool} | isEqualToNode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def appendChild(self, child):
"""
Make the given L{Node} the last child of this node.
@param child: The L{Node} which will become a child of this node.
@raise TypeError: If C{child} is not a C{Node} instance.
"""
if not isinstance(child, Node):
raise TypeError("expected Node instance")
self.childNodes.append(child)
child.parentNode = self | Make the given L{Node} the last child of this node.
@param child: The L{Node} which will become a child of this node.
@raise TypeError: If C{child} is not a C{Node} instance. | appendChild | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.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.