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 abortRequest(self, streamID):
"""
Called by L{H2Stream} objects to request early termination of a stream.
This emits a RstStream frame and then removes all stream state.
@param streamID: The ID of the stream to write the data to.
@type streamID: L{int}
"""
self.conn.reset_stream(streamID)
self.transport.write(self.conn.data_to_send())
self._requestDone(streamID) | Called by L{H2Stream} objects to request early termination of a stream.
This emits a RstStream frame and then removes all stream state.
@param streamID: The ID of the stream to write the data to.
@type streamID: L{int} | abortRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def _requestDone(self, streamID):
"""
Called internally by the data sending loop to clean up state that was
being used for the stream. Called when the stream is complete.
@param streamID: The ID of the stream to clean up state for.
@type streamID: L{int}
"""
del self._outboundStreamQueues[streamID]
self.priority.remove_stream(streamID)
del self.streams[streamID]
cleanupCallback = self._streamCleanupCallbacks.pop(streamID)
cleanupCallback.callback(streamID) | Called internally by the data sending loop to clean up state that was
being used for the stream. Called when the stream is complete.
@param streamID: The ID of the stream to clean up state for.
@type streamID: L{int} | _requestDone | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def remainingOutboundWindow(self, streamID):
"""
Called to determine how much room is left in the send window for a
given stream. Allows us to handle blocking and unblocking producers.
@param streamID: The ID of the stream whose flow control window we'll
check.
@type streamID: L{int}
@return: The amount of room remaining in the send window for the given
stream, including the data queued to be sent.
@rtype: L{int}
"""
# TODO: This involves a fair bit of looping and computation for
# something that is called a lot. Consider caching values somewhere.
windowSize = self.conn.local_flow_control_window(streamID)
sendQueue = self._outboundStreamQueues[streamID]
alreadyConsumed = sum(
len(chunk) for chunk in sendQueue
if chunk is not _END_STREAM_SENTINEL
)
return windowSize - alreadyConsumed | Called to determine how much room is left in the send window for a
given stream. Allows us to handle blocking and unblocking producers.
@param streamID: The ID of the stream whose flow control window we'll
check.
@type streamID: L{int}
@return: The amount of room remaining in the send window for the given
stream, including the data queued to be sent.
@rtype: L{int} | remainingOutboundWindow | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def _handleWindowUpdate(self, event):
"""
Manage flow control windows.
Streams that are blocked on flow control will register themselves with
the connection. This will fire deferreds that wake those streams up and
allow them to continue processing.
@param event: The Hyper-h2 event that encodes information about the
flow control window change.
@type event: L{h2.events.WindowUpdated}
"""
streamID = event.stream_id
if streamID:
if not self._streamIsActive(streamID):
# We may have already cleaned up our stream state, making this
# a late WINDOW_UPDATE frame. That's fine: the update is
# unnecessary but benign. We'll ignore it.
return
# If we haven't got any data to send, don't unblock the stream. If
# we do, we'll eventually get an exception inside the
# _sendPrioritisedData loop some time later.
if self._outboundStreamQueues.get(streamID):
self.priority.unblock(streamID)
self.streams[streamID].windowUpdated()
else:
# Update strictly applies to all streams.
for stream in self.streams.values():
stream.windowUpdated()
# If we still have data to send for this stream, unblock it.
if self._outboundStreamQueues.get(stream.streamID):
self.priority.unblock(stream.streamID) | Manage flow control windows.
Streams that are blocked on flow control will register themselves with
the connection. This will fire deferreds that wake those streams up and
allow them to continue processing.
@param event: The Hyper-h2 event that encodes information about the
flow control window change.
@type event: L{h2.events.WindowUpdated} | _handleWindowUpdate | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def getPeer(self):
"""
Get the remote address of this connection.
Treat this method with caution. It is the unfortunate result of the
CGI and Jabber standards, but should not be considered reliable for
the usual host of reasons; port forwarding, proxying, firewalls, IP
masquerading, etc.
@return: An L{IAddress} provider.
"""
return self.transport.getPeer() | Get the remote address of this connection.
Treat this method with caution. It is the unfortunate result of the
CGI and Jabber standards, but should not be considered reliable for
the usual host of reasons; port forwarding, proxying, firewalls, IP
masquerading, etc.
@return: An L{IAddress} provider. | getPeer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def getHost(self):
"""
Similar to getPeer, but returns an address describing this side of the
connection.
@return: An L{IAddress} provider.
"""
return self.transport.getHost() | Similar to getPeer, but returns an address describing this side of the
connection.
@return: An L{IAddress} provider. | getHost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def openStreamWindow(self, streamID, increment):
"""
Open the stream window by a given increment.
@param streamID: The ID of the stream whose window needs to be opened.
@type streamID: L{int}
@param increment: The amount by which the stream window must be
incremented.
@type increment: L{int}
"""
self.conn.acknowledge_received_data(increment, streamID)
data = self.conn.data_to_send()
if data:
self.transport.write(data) | Open the stream window by a given increment.
@param streamID: The ID of the stream whose window needs to be opened.
@type streamID: L{int}
@param increment: The amount by which the stream window must be
incremented.
@type increment: L{int} | openStreamWindow | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def _isSecure(self):
"""
Returns L{True} if this channel is using a secure transport.
@returns: L{True} if this channel is secure.
@rtype: L{bool}
"""
# A channel is secure if its transport is ISSLTransport.
return ISSLTransport(self.transport, None) is not None | Returns L{True} if this channel is using a secure transport.
@returns: L{True} if this channel is secure.
@rtype: L{bool} | _isSecure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def _send100Continue(self, streamID):
"""
Sends a 100 Continue response, used to signal to clients that further
processing will be performed.
@param streamID: The ID of the stream that needs the 100 Continue
response
@type streamID: L{int}
"""
headers = [(b':status', b'100')]
self.conn.send_headers(headers=headers, stream_id=streamID)
self.transport.write(self.conn.data_to_send()) | Sends a 100 Continue response, used to signal to clients that further
processing will be performed.
@param streamID: The ID of the stream that needs the 100 Continue
response
@type streamID: L{int} | _send100Continue | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def _respondToBadRequestAndDisconnect(self, streamID):
"""
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.
Unlike in the HTTP/1.1 case, this does not actually disconnect the
underlying transport: there's no need. This instead just sends a 400
response and terminates the stream.
@param streamID: The ID of the stream that needs the 100 Continue
response
@type streamID: L{int}
"""
headers = [(b':status', b'400')]
self.conn.send_headers(
headers=headers,
stream_id=streamID,
end_stream=True
)
self.transport.write(self.conn.data_to_send())
stream = self.streams[streamID]
stream.connectionLost(ConnectionLost("Invalid request"))
self._requestDone(streamID) | 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.
Unlike in the HTTP/1.1 case, this does not actually disconnect the
underlying transport: there's no need. This instead just sends a 400
response and terminates the stream.
@param streamID: The ID of the stream that needs the 100 Continue
response
@type streamID: L{int} | _respondToBadRequestAndDisconnect | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def _streamIsActive(self, streamID):
"""
Checks whether Twisted has still got state for a given stream and so
can process events for that stream.
@param streamID: The ID of the stream that needs processing.
@type streamID: L{int}
@return: Whether the stream still has state allocated.
@rtype: L{bool}
"""
return streamID in self.streams | Checks whether Twisted has still got state for a given stream and so
can process events for that stream.
@param streamID: The ID of the stream that needs processing.
@type streamID: L{int}
@return: Whether the stream still has state allocated.
@rtype: L{bool} | _streamIsActive | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def __init__(self, streamID, connection, headers,
requestFactory, site, factory):
"""
Initialize this HTTP/2 stream.
@param streamID: The numerical stream ID that this object corresponds
to.
@type streamID: L{int}
@param connection: The HTTP/2 connection this stream belongs to.
@type connection: L{H2Connection}
@param headers: The HTTP/2 request headers.
@type headers: A L{list} of L{tuple}s of header name and header value,
both as L{bytes}.
@param requestFactory: A function that builds appropriate request
request objects.
@type requestFactory: A callable that returns a
L{twisted.web.iweb.IRequest}.
@param site: The L{twisted.web.server.Site} object this stream belongs
to, if any.
@type site: L{twisted.web.server.Site}
@param factory: The L{twisted.web.http.HTTPFactory} object that
constructed this stream's parent connection.
@type factory: L{twisted.web.http.HTTPFactory}
"""
self.streamID = streamID
self.site = site
self.factory = factory
self.producing = True
self.command = None
self.path = None
self.producer = None
self._producerProducing = False
self._hasStreamingProducer = None
self._inboundDataBuffer = deque()
self._conn = connection
self._request = requestFactory(self, queued=False)
self._buffer = io.BytesIO()
self._convertHeaders(headers) | Initialize this HTTP/2 stream.
@param streamID: The numerical stream ID that this object corresponds
to.
@type streamID: L{int}
@param connection: The HTTP/2 connection this stream belongs to.
@type connection: L{H2Connection}
@param headers: The HTTP/2 request headers.
@type headers: A L{list} of L{tuple}s of header name and header value,
both as L{bytes}.
@param requestFactory: A function that builds appropriate request
request objects.
@type requestFactory: A callable that returns a
L{twisted.web.iweb.IRequest}.
@param site: The L{twisted.web.server.Site} object this stream belongs
to, if any.
@type site: L{twisted.web.server.Site}
@param factory: The L{twisted.web.http.HTTPFactory} object that
constructed this stream's parent connection.
@type factory: L{twisted.web.http.HTTPFactory} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def _convertHeaders(self, headers):
"""
This method converts the HTTP/2 header set into something that looks
like HTTP/1.1. In particular, it strips the 'special' headers and adds
a Host: header.
@param headers: The HTTP/2 header set.
@type headers: A L{list} of L{tuple}s of header name and header value,
both as L{bytes}.
"""
gotLength = False
for header in headers:
if not header[0].startswith(b':'):
gotLength = (
_addHeaderToRequest(self._request, header) or gotLength
)
elif header[0] == b':method':
self.command = header[1]
elif header[0] == b':path':
self.path = header[1]
elif header[0] == b':authority':
# This is essentially the Host: header from HTTP/1.1
_addHeaderToRequest(self._request, (b'host', header[1]))
if not gotLength:
if self.command in (b'GET', b'HEAD'):
self._request.gotLength(0)
else:
self._request.gotLength(None)
self._request.parseCookies()
expectContinue = self._request.requestHeaders.getRawHeaders(b'expect')
if expectContinue and expectContinue[0].lower() == b'100-continue':
self._send100Continue() | This method converts the HTTP/2 header set into something that looks
like HTTP/1.1. In particular, it strips the 'special' headers and adds
a Host: header.
@param headers: The HTTP/2 header set.
@type headers: A L{list} of L{tuple}s of header name and header value,
both as L{bytes}. | _convertHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def receiveDataChunk(self, data, flowControlledLength):
"""
Called when the connection has received a chunk of data from the
underlying transport. If the stream has been registered with a
consumer, and is currently able to push data, immediately passes it
through. Otherwise, buffers the chunk until we can start producing.
@param data: The chunk of data that was received.
@type data: L{bytes}
@param flowControlledLength: The total flow controlled length of this
chunk, which is used when we want to re-open the window. May be
different to C{len(data)}.
@type flowControlledLength: L{int}
"""
if not self.producing:
# Buffer data.
self._inboundDataBuffer.append((data, flowControlledLength))
else:
self._request.handleContentChunk(data)
self._conn.openStreamWindow(self.streamID, flowControlledLength) | Called when the connection has received a chunk of data from the
underlying transport. If the stream has been registered with a
consumer, and is currently able to push data, immediately passes it
through. Otherwise, buffers the chunk until we can start producing.
@param data: The chunk of data that was received.
@type data: L{bytes}
@param flowControlledLength: The total flow controlled length of this
chunk, which is used when we want to re-open the window. May be
different to C{len(data)}.
@type flowControlledLength: L{int} | receiveDataChunk | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def requestComplete(self):
"""
Called by the L{H2Connection} when the all data for a request has been
received. Currently, with the legacy L{twisted.web.http.Request}
object, just calls requestReceived unless the producer wants us to be
quiet.
"""
if self.producing:
self._request.requestReceived(self.command, self.path, b'HTTP/2')
else:
self._inboundDataBuffer.append((_END_STREAM_SENTINEL, None)) | Called by the L{H2Connection} when the all data for a request has been
received. Currently, with the legacy L{twisted.web.http.Request}
object, just calls requestReceived unless the producer wants us to be
quiet. | requestComplete | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def connectionLost(self, reason):
"""
Called by the L{H2Connection} when a connection is lost or a stream is
reset.
@param reason: The reason the connection was lost.
@type reason: L{str}
"""
self._request.connectionLost(reason) | Called by the L{H2Connection} when a connection is lost or a stream is
reset.
@param reason: The reason the connection was lost.
@type reason: L{str} | connectionLost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def windowUpdated(self):
"""
Called by the L{H2Connection} when this stream's flow control window
has been opened.
"""
# If we don't have a producer, we have no-one to tell.
if not self.producer:
return
# If we're not blocked on flow control, we don't care.
if self._producerProducing:
return
# We check whether the stream's flow control window is actually above
# 0, and then, if a producer is registered and we still have space in
# the window, we unblock it.
remainingWindow = self._conn.remainingOutboundWindow(self.streamID)
if not remainingWindow > 0:
return
# We have a producer and space in the window, so that producer can
# start producing again!
self._producerProducing = True
self.producer.resumeProducing() | Called by the L{H2Connection} when this stream's flow control window
has been opened. | windowUpdated | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def flowControlBlocked(self):
"""
Called by the L{H2Connection} when this stream's flow control window
has been exhausted.
"""
if not self.producer:
return
if self._producerProducing:
self.producer.pauseProducing()
self._producerProducing = False | Called by the L{H2Connection} when this stream's flow control window
has been exhausted. | flowControlBlocked | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def writeHeaders(self, version, code, reason, headers):
"""
Called by the consumer to write headers to the stream.
@param version: The HTTP version.
@type version: L{bytes}
@param code: The status code.
@type code: L{int}
@param reason: The reason phrase. Ignored in HTTP/2.
@type reason: L{bytes}
@param headers: The HTTP response headers.
@type: Any iterable of two-tuples of L{bytes}, representing header
names and header values.
"""
self._conn.writeHeaders(version, code, reason, headers, self.streamID) | Called by the consumer to write headers to the stream.
@param version: The HTTP version.
@type version: L{bytes}
@param code: The status code.
@type code: L{int}
@param reason: The reason phrase. Ignored in HTTP/2.
@type reason: L{bytes}
@param headers: The HTTP response headers.
@type: Any iterable of two-tuples of L{bytes}, representing header
names and header values. | writeHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def requestDone(self, request):
"""
Called by a consumer to clean up whatever permanent state is in use.
@param request: The request calling the method.
@type request: L{twisted.web.iweb.IRequest}
"""
self._conn.endRequest(self.streamID) | Called by a consumer to clean up whatever permanent state is in use.
@param request: The request calling the method.
@type request: L{twisted.web.iweb.IRequest} | requestDone | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def _send100Continue(self):
"""
Sends a 100 Continue response, used to signal to clients that further
processing will be performed.
"""
self._conn._send100Continue(self.streamID) | 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/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.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.
Unlike in the HTTP/1.1 case, this does not actually disconnect the
underlying transport: there's no need. This instead just sends a 400
response and terminates the stream.
"""
self._conn._respondToBadRequestAndDisconnect(self.streamID) | 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.
Unlike in the HTTP/1.1 case, this does not actually disconnect the
underlying transport: there's no need. This instead just sends a 400
response and terminates the stream. | _respondToBadRequestAndDisconnect | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def write(self, data):
"""
Write a single chunk of data into a data frame.
@param data: The data chunk to send.
@type data: L{bytes}
"""
self._conn.writeDataToStream(self.streamID, data)
return | Write a single chunk of data into a data frame.
@param data: The data chunk to send.
@type data: L{bytes} | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def writeSequence(self, iovec):
"""
Write a sequence of chunks of data into data frames.
@param iovec: A sequence of chunks to send.
@type iovec: An iterable of L{bytes} chunks.
"""
for chunk in iovec:
self.write(chunk) | Write a sequence of chunks of data into data frames.
@param iovec: A sequence of chunks to send.
@type iovec: An iterable of L{bytes} chunks. | writeSequence | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def loseConnection(self):
"""
Close the connection after writing all pending data.
"""
self._conn.endRequest(self.streamID) | Close the connection after writing all pending data. | loseConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def abortConnection(self):
"""
Forcefully abort the connection by sending a RstStream frame.
"""
self._conn.abortRequest(self.streamID) | Forcefully abort the connection by sending a RstStream frame. | abortConnection | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def getPeer(self):
"""
Get information about the peer.
"""
return self._conn.getPeer() | Get information about the peer. | getPeer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def getHost(self):
"""
Similar to getPeer, but for this side of the connection.
"""
return self._conn.getHost() | Similar to getPeer, but for this side of the connection. | getHost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def isSecure(self):
"""
Returns L{True} if this channel is using a secure transport.
@returns: L{True} if this channel is secure.
@rtype: L{bool}
"""
return self._conn._isSecure() | Returns L{True} if this channel is using a secure transport.
@returns: L{True} if this channel is secure.
@rtype: L{bool} | isSecure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.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.
@param producer: The producer to register.
@type producer: L{IProducer} provider
@param streaming: L{True} if C{producer} provides L{IPushProducer},
L{False} if C{producer} provides L{IPullProducer}.
@type streaming: L{bool}
@raise RuntimeError: If a producer is already registered.
@return: L{None}
"""
if self.producer:
raise ValueError(
"registering producer %s before previous one (%s) was "
"unregistered" % (producer, self.producer))
if not streaming:
self.hasStreamingProducer = False
producer = _PullToPush(producer, self)
producer.startStreaming()
else:
self.hasStreamingProducer = True
self.producer = producer
self._producerProducing = True | 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.
@param producer: The producer to register.
@type producer: L{IProducer} provider
@param streaming: L{True} if C{producer} provides L{IPushProducer},
L{False} if C{producer} provides L{IPullProducer}.
@type streaming: L{bool}
@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/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def unregisterProducer(self):
"""
@see: L{IConsumer.unregisterProducer}
"""
# When the producer is unregistered, we're done.
if self.producer is not None and not self.hasStreamingProducer:
self.producer.stopStreaming()
self._producerProducing = False
self.producer = None
self.hasStreamingProducer = None | @see: L{IConsumer.unregisterProducer} | unregisterProducer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def stopProducing(self):
"""
@see: L{IProducer.stopProducing}
"""
self.producing = False
self.abortConnection() | @see: L{IProducer.stopProducing} | stopProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def pauseProducing(self):
"""
@see: L{IPushProducer.pauseProducing}
"""
self.producing = False | @see: L{IPushProducer.pauseProducing} | pauseProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def resumeProducing(self):
"""
@see: L{IPushProducer.resumeProducing}
"""
self.producing = True
consumedLength = 0
while self.producing and self._inboundDataBuffer:
# Allow for pauseProducing to be called in response to a call to
# resumeProducing.
chunk, flowControlledLength = self._inboundDataBuffer.popleft()
if chunk is _END_STREAM_SENTINEL:
self.requestComplete()
else:
consumedLength += flowControlledLength
self._request.handleContentChunk(chunk)
self._conn.openStreamWindow(self.streamID, consumedLength) | @see: L{IPushProducer.resumeProducing} | resumeProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def _addHeaderToRequest(request, header):
"""
Add a header tuple to a request header object.
@param request: The request to add the header tuple to.
@type request: L{twisted.web.http.Request}
@param header: The header tuple to add to the request.
@type header: A L{tuple} with two elements, the header name and header
value, both as L{bytes}.
@return: If the header being added was the C{Content-Length} header.
@rtype: L{bool}
"""
requestHeaders = request.requestHeaders
name, value = header
values = requestHeaders.getRawHeaders(name)
if values is not None:
values.append(value)
else:
requestHeaders.setRawHeaders(name, [value])
if name == b'content-length':
request.gotLength(int(value))
return True
return False | Add a header tuple to a request header object.
@param request: The request to add the header tuple to.
@type request: L{twisted.web.http.Request}
@param header: The header tuple to add to the request.
@type header: A L{tuple} with two elements, the header name and header
value, both as L{bytes}.
@return: If the header being added was the C{Content-Length} header.
@rtype: L{bool} | _addHeaderToRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_http2.py | MIT |
def getHeader(key):
"""
Get an HTTP request header.
@type key: L{bytes} or L{str}
@param key: The name of the header to get the value of.
@rtype: L{bytes} or L{str} or L{None}
@return: The value of the specified header, or L{None} if that header
was not present in the request. The string type of the result
matches the type of C{key}.
""" | Get an HTTP request header.
@type key: L{bytes} or L{str}
@param key: The name of the header to get the value of.
@rtype: L{bytes} or L{str} or L{None}
@return: The value of the specified header, or L{None} if that header
was not present in the request. The string type of the result
matches the type of C{key}. | getHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def getCookie(key):
"""
Get a cookie that was sent from the network.
@type key: L{bytes}
@param key: The name of the cookie to get.
@rtype: L{bytes} or L{None}
@returns: The value of the specified cookie, or L{None} if that cookie
was not present in the request.
""" | Get a cookie that was sent from the network.
@type key: L{bytes}
@param key: The name of the cookie to get.
@rtype: L{bytes} or L{None}
@returns: The value of the specified cookie, or L{None} if that cookie
was not present in the request. | getCookie | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def getAllHeaders():
"""
Return dictionary mapping the names of all received headers to the last
value received for each.
Since this method does not return all header information,
C{requestHeaders.getAllRawHeaders()} may be preferred.
""" | Return dictionary mapping the names of all received headers to the last
value received for each.
Since this method does not return all header information,
C{requestHeaders.getAllRawHeaders()} may be preferred. | getAllHeaders | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def getRequestHostname():
"""
Get the hostname that the user passed in to the request.
This will either use the Host: header (if it is available) or the
host we are listening on if the header is unavailable.
@returns: the requested hostname
@rtype: L{str}
""" | Get the hostname that the user passed in to the request.
This will either use the Host: header (if it is available) or the
host we are listening on if the header is unavailable.
@returns: the requested hostname
@rtype: L{str} | getRequestHostname | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def getHost():
"""
Get my originally requesting transport's host.
@return: An L{IAddress<twisted.internet.interfaces.IAddress>}.
""" | Get my originally requesting transport's host.
@return: An L{IAddress<twisted.internet.interfaces.IAddress>}. | getHost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def getClientAddress():
"""
Return the address of the client who submitted this request.
The address may not be a network address. Callers must check
its type before using it.
@since: 18.4
@return: the client's address.
@rtype: an L{IAddress} provider.
""" | Return the address of the client who submitted this request.
The address may not be a network address. Callers must check
its type before using it.
@since: 18.4
@return: the client's address.
@rtype: an L{IAddress} provider. | getClientAddress | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def getClientIP():
"""
Return the IP address of the client who submitted this request.
This method is B{deprecated}. See L{getClientAddress} instead.
@returns: the client IP address or L{None} if the request was submitted
over a transport where IP addresses do not make sense.
@rtype: L{str} or L{None}
""" | Return the IP address of the client who submitted this request.
This method is B{deprecated}. See L{getClientAddress} instead.
@returns: the client IP address or L{None} if the request was submitted
over a transport where IP addresses do not make sense.
@rtype: L{str} or L{None} | getClientIP | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def getUser():
"""
Return the HTTP user sent with this request, if any.
If no user was supplied, return the empty string.
@returns: the HTTP user, if any
@rtype: L{str}
""" | Return the HTTP user sent with this request, if any.
If no user was supplied, return the empty string.
@returns: the HTTP user, if any
@rtype: L{str} | getUser | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def getPassword():
"""
Return the HTTP password sent with this request, if any.
If no password was supplied, return the empty string.
@returns: the HTTP password, if any
@rtype: L{str}
""" | Return the HTTP password sent with this request, if any.
If no password was supplied, return the empty string.
@returns: the HTTP password, if any
@rtype: L{str} | getPassword | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def isSecure():
"""
Return True if this request is using a secure transport.
Normally this method returns True if this request's HTTPChannel
instance is using a transport that implements ISSLTransport.
This will also return True if setHost() has been called
with ssl=True.
@returns: True if this request is secure
@rtype: C{bool}
""" | Return True if this request is using a secure transport.
Normally this method returns True if this request's HTTPChannel
instance is using a transport that implements ISSLTransport.
This will also return True if setHost() has been called
with ssl=True.
@returns: True if this request is secure
@rtype: C{bool} | isSecure | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def getSession(sessionInterface=None):
"""
Look up the session associated with this request or create a new one if
there is not one.
@return: The L{Session} instance identified by the session cookie in
the request, or the C{sessionInterface} component of that session
if C{sessionInterface} is specified.
""" | Look up the session associated with this request or create a new one if
there is not one.
@return: The L{Session} instance identified by the session cookie in
the request, or the C{sessionInterface} component of that session
if C{sessionInterface} is specified. | getSession | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def URLPath():
"""
@return: A L{URLPath<twisted.python.urlpath.URLPath>} instance
which identifies the URL for which this request is.
""" | @return: A L{URLPath<twisted.python.urlpath.URLPath>} instance
which identifies the URL for which this request is. | URLPath | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def prePathURL():
"""
At any time during resource traversal or resource rendering,
returns an absolute URL to the most nested resource which has
yet been reached.
@see: {twisted.web.server.Request.prepath}
@return: An absolute URL.
@type: L{bytes}
""" | At any time during resource traversal or resource rendering,
returns an absolute URL to the most nested resource which has
yet been reached.
@see: {twisted.web.server.Request.prepath}
@return: An absolute URL.
@type: L{bytes} | prePathURL | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def rememberRootURL():
"""
Remember the currently-processed part of the URL for later
recalling.
""" | Remember the currently-processed part of the URL for later
recalling. | rememberRootURL | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def getRootURL():
"""
Get a previously-remembered URL.
@return: An absolute URL.
@type: L{bytes}
""" | Get a previously-remembered URL.
@return: An absolute URL.
@type: L{bytes} | getRootURL | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def finish():
"""
Indicate that the response to this request is complete.
""" | Indicate that the response to this request is complete. | finish | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def write(data):
"""
Write some data to the body of the response to this request. Response
headers are written the first time this method is called, after which
new response headers may not be added.
@param data: Bytes of the response body.
@type data: L{bytes}
""" | Write some data to the body of the response to this request. Response
headers are written the first time this method is called, after which
new response headers may not be added.
@param data: Bytes of the response body.
@type data: L{bytes} | write | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def addCookie(k, v, expires=None, domain=None, path=None, max_age=None, comment=None, secure=None):
"""
Set an outgoing HTTP cookie.
In general, you should consider using sessions instead of cookies, see
L{twisted.web.server.Request.getSession} and the
L{twisted.web.server.Session} class for details.
""" | Set an outgoing HTTP cookie.
In general, you should consider using sessions instead of cookies, see
L{twisted.web.server.Request.getSession} and the
L{twisted.web.server.Session} class for details. | addCookie | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def setResponseCode(code, message=None):
"""
Set the HTTP response code.
@type code: L{int}
@type message: L{bytes}
""" | Set the HTTP response code.
@type code: L{int}
@type message: L{bytes} | setResponseCode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def setHeader(k, v):
"""
Set an HTTP response header. Overrides any previously set values for
this header.
@type k: L{bytes} or L{str}
@param k: The name of the header for which to set the value.
@type v: L{bytes} or L{str}
@param v: The value to set for the named header. A L{str} will be
UTF-8 encoded, which may not interoperable with other
implementations. Avoid passing non-ASCII characters if possible.
""" | Set an HTTP response header. Overrides any previously set values for
this header.
@type k: L{bytes} or L{str}
@param k: The name of the header for which to set the value.
@type v: L{bytes} or L{str}
@param v: The value to set for the named header. A L{str} will be
UTF-8 encoded, which may not interoperable with other
implementations. Avoid passing non-ASCII characters if possible. | setHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def redirect(url):
"""
Utility function that does a redirect.
The request should have finish() called after this.
""" | Utility function that does a redirect.
The request should have finish() called after this. | redirect | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def setLastModified(when):
"""
Set the C{Last-Modified} time for the response to this request.
If I am called more than once, I ignore attempts to set Last-Modified
earlier, only replacing the Last-Modified time if it is to a later
value.
If I am a conditional request, I may modify my response code to
L{NOT_MODIFIED<http.NOT_MODIFIED>} if appropriate for the time given.
@param when: The last time the resource being returned was modified, in
seconds since the epoch.
@type when: L{int}, L{long} or L{float}
@return: If I am a C{If-Modified-Since} conditional request and the time
given is not newer than the condition, I return
L{CACHED<http.CACHED>} to indicate that you should write no body.
Otherwise, I return a false value.
""" | Set the C{Last-Modified} time for the response to this request.
If I am called more than once, I ignore attempts to set Last-Modified
earlier, only replacing the Last-Modified time if it is to a later
value.
If I am a conditional request, I may modify my response code to
L{NOT_MODIFIED<http.NOT_MODIFIED>} if appropriate for the time given.
@param when: The last time the resource being returned was modified, in
seconds since the epoch.
@type when: L{int}, L{long} or L{float}
@return: If I am a C{If-Modified-Since} conditional request and the time
given is not newer than the condition, I return
L{CACHED<http.CACHED>} to indicate that you should write no body.
Otherwise, I return a false value. | setLastModified | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def setETag(etag):
"""
Set an C{entity tag} for the outgoing response.
That's "entity tag" as in the HTTP/1.1 I{ETag} header, "used for
comparing two or more entities from the same requested resource."
If I am a conditional request, I may modify my response code to
L{NOT_MODIFIED<http.NOT_MODIFIED>} or
L{PRECONDITION_FAILED<http.PRECONDITION_FAILED>}, if appropriate for the
tag given.
@param etag: The entity tag for the resource being returned.
@type etag: L{str}
@return: If I am a C{If-None-Match} conditional request and the tag
matches one in the request, I return L{CACHED<http.CACHED>} to
indicate that you should write no body. Otherwise, I return a
false value.
""" | Set an C{entity tag} for the outgoing response.
That's "entity tag" as in the HTTP/1.1 I{ETag} header, "used for
comparing two or more entities from the same requested resource."
If I am a conditional request, I may modify my response code to
L{NOT_MODIFIED<http.NOT_MODIFIED>} or
L{PRECONDITION_FAILED<http.PRECONDITION_FAILED>}, if appropriate for the
tag given.
@param etag: The entity tag for the resource being returned.
@type etag: L{str}
@return: If I am a C{If-None-Match} conditional request and the tag
matches one in the request, I return L{CACHED<http.CACHED>} to
indicate that you should write no body. Otherwise, I return a
false value. | setETag | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def setHost(host, port, ssl=0):
"""
Change the host and port the request thinks it's using.
This method is useful for working with reverse HTTP proxies (e.g. both
Squid and Apache's mod_proxy can do this), when the address the HTTP
client is using is different than the one we're listening on.
For example, Apache may be listening on https://www.example.com, and
then forwarding requests to http://localhost:8080, but we don't want
HTML produced by Twisted to say 'http://localhost:8080', they should
say 'https://www.example.com', so we do::
request.setHost('www.example.com', 443, ssl=1)
""" | Change the host and port the request thinks it's using.
This method is useful for working with reverse HTTP proxies (e.g. both
Squid and Apache's mod_proxy can do this), when the address the HTTP
client is using is different than the one we're listening on.
For example, Apache may be listening on https://www.example.com, and
then forwarding requests to http://localhost:8080, but we don't want
HTML produced by Twisted to say 'http://localhost:8080', they should
say 'https://www.example.com', so we do::
request.setHost('www.example.com', 443, ssl=1) | setHost | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def __call__(channel):
"""
Create an L{IRequest} that is operating on the given channel. There
must only be one L{IRequest} object processing at any given time on a
channel.
@param channel: A L{twisted.web.http.HTTPChannel} object.
@type channel: L{twisted.web.http.HTTPChannel}
@return: A request object.
@rtype: L{IRequest}
""" | Create an L{IRequest} that is operating on the given channel. There
must only be one L{IRequest} object processing at any given time on a
channel.
@param channel: A L{twisted.web.http.HTTPChannel} object.
@type channel: L{twisted.web.http.HTTPChannel}
@return: A request object.
@rtype: L{IRequest} | __call__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def __call__(timestamp, request):
"""
Generate a line for the access log.
@param timestamp: The time at which the request was completed in the
standard format for access logs.
@type timestamp: L{unicode}
@param request: The request object about which to log.
@type request: L{twisted.web.server.Request}
@return: One line describing the request without a trailing newline.
@rtype: L{unicode}
""" | Generate a line for the access log.
@param timestamp: The time at which the request was completed in the
standard format for access logs.
@type timestamp: L{unicode}
@param request: The request object about which to log.
@type request: L{twisted.web.server.Request}
@return: One line describing the request without a trailing newline.
@rtype: L{unicode} | __call__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def getChallenge(request):
"""
Generate a new challenge to be sent to a client.
@type peer: L{twisted.web.http.Request}
@param peer: The request the response to which this challenge will be
included.
@rtype: L{dict}
@return: A mapping from L{str} challenge fields to associated L{str}
values.
""" | Generate a new challenge to be sent to a client.
@type peer: L{twisted.web.http.Request}
@param peer: The request the response to which this challenge will be
included.
@rtype: L{dict}
@return: A mapping from L{str} challenge fields to associated L{str}
values. | getChallenge | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def decode(response, request):
"""
Create a credentials object from the given response.
@type response: L{str}
@param response: scheme specific response string
@type request: L{twisted.web.http.Request}
@param request: The request being processed (from which the response
was taken).
@raise twisted.cred.error.LoginFailed: If the response is invalid.
@rtype: L{twisted.cred.credentials.ICredentials} provider
@return: The credentials represented by the given response.
""" | Create a credentials object from the given response.
@type response: L{str}
@param response: scheme specific response string
@type request: L{twisted.web.http.Request}
@param request: The request being processed (from which the response
was taken).
@raise twisted.cred.error.LoginFailed: If the response is invalid.
@rtype: L{twisted.cred.credentials.ICredentials} provider
@return: The credentials represented by the given response. | decode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def startProducing(consumer):
"""
Start producing to the given
L{IConsumer<twisted.internet.interfaces.IConsumer>} provider.
@return: A L{Deferred<twisted.internet.defer.Deferred>} which fires with
L{None} when all bytes have been produced or with a
L{Failure<twisted.python.failure.Failure>} if there is any problem
before all bytes have been produced.
""" | Start producing to the given
L{IConsumer<twisted.internet.interfaces.IConsumer>} provider.
@return: A L{Deferred<twisted.internet.defer.Deferred>} which fires with
L{None} when all bytes have been produced or with a
L{Failure<twisted.python.failure.Failure>} if there is any problem
before all bytes have been produced. | startProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def stopProducing():
"""
In addition to the standard behavior of
L{IProducer.stopProducing<twisted.internet.interfaces.IProducer.stopProducing>}
(stop producing data), make sure the
L{Deferred<twisted.internet.defer.Deferred>} returned by
C{startProducing} is never fired.
""" | In addition to the standard behavior of
L{IProducer.stopProducing<twisted.internet.interfaces.IProducer.stopProducing>}
(stop producing data), make sure the
L{Deferred<twisted.internet.defer.Deferred>} returned by
C{startProducing} is never fired. | stopProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def lookupRenderMethod(name):
"""
Look up and return the render method associated with the given name.
@type name: L{str}
@param name: The value of a render directive encountered in the
document returned by a call to L{IRenderable.render}.
@return: A two-argument callable which will be invoked with the request
being responded to and the tag object on which the render directive
was encountered.
""" | Look up and return the render method associated with the given name.
@type name: L{str}
@param name: The value of a render directive encountered in the
document returned by a call to L{IRenderable.render}.
@return: A two-argument callable which will be invoked with the request
being responded to and the tag object on which the render directive
was encountered. | lookupRenderMethod | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def render(request):
"""
Get the document for this L{IRenderable}.
@type request: L{IRequest} provider or L{None}
@param request: The request in response to which this method is being
invoked.
@return: An object which can be flattened.
""" | Get the document for this L{IRenderable}.
@type request: L{IRequest} provider or L{None}
@param request: The request in response to which this method is being
invoked.
@return: An object which can be flattened. | render | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def load():
"""
Load a template suitable for rendering.
@return: a L{list} of L{list}s, L{unicode} objects, C{Element}s and
other L{IRenderable} providers.
""" | Load a template suitable for rendering.
@return: a L{list} of L{list}s, L{unicode} objects, C{Element}s and
other L{IRenderable} providers. | load | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def deliverBody(protocol):
"""
Register an L{IProtocol<twisted.internet.interfaces.IProtocol>} provider
to receive the response body.
The protocol will be connected to a transport which provides
L{IPushProducer}. The protocol's C{connectionLost} method will be
called with:
- ResponseDone, which indicates that all bytes from the response
have been successfully delivered.
- PotentialDataLoss, which indicates that it cannot be determined
if the entire response body has been delivered. This only occurs
when making requests to HTTP servers which do not set
I{Content-Length} or a I{Transfer-Encoding} in the response.
- ResponseFailed, which indicates that some bytes from the response
were lost. The C{reasons} attribute of the exception may provide
more specific indications as to why.
""" | Register an L{IProtocol<twisted.internet.interfaces.IProtocol>} provider
to receive the response body.
The protocol will be connected to a transport which provides
L{IPushProducer}. The protocol's C{connectionLost} method will be
called with:
- ResponseDone, which indicates that all bytes from the response
have been successfully delivered.
- PotentialDataLoss, which indicates that it cannot be determined
if the entire response body has been delivered. This only occurs
when making requests to HTTP servers which do not set
I{Content-Length} or a I{Transfer-Encoding} in the response.
- ResponseFailed, which indicates that some bytes from the response
were lost. The C{reasons} attribute of the exception may provide
more specific indications as to why. | deliverBody | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def setPreviousResponse(response):
"""
Set the reference to the previous L{IResponse}.
The value of the previous response can be read via
L{IResponse.previousResponse}.
""" | Set the reference to the previous L{IResponse}.
The value of the previous response can be read via
L{IResponse.previousResponse}. | setPreviousResponse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def encode(data):
"""
Encode the data given and return the result.
@param data: The content to encode.
@type data: L{str}
@return: The encoded data.
@rtype: L{str}
""" | Encode the data given and return the result.
@param data: The content to encode.
@type data: L{str}
@return: The encoded data.
@rtype: L{str} | encode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def finish():
"""
Callback called when the request is closing.
@return: If necessary, the pending data accumulated from previous
C{encode} calls.
@rtype: L{str}
""" | Callback called when the request is closing.
@return: If necessary, the pending data accumulated from previous
C{encode} calls.
@rtype: L{str} | finish | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def encoderForRequest(request):
"""
If applicable, returns a L{_IRequestEncoder} instance which will encode
the request.
""" | If applicable, returns a L{_IRequestEncoder} instance which will encode
the request. | encoderForRequest | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def request(method, uri, headers=None, bodyProducer=None):
"""
Request the resource at the given location.
@param method: The request method to use, such as C{"GET"}, C{"HEAD"},
C{"PUT"}, C{"POST"}, etc.
@type method: L{bytes}
@param uri: The location of the resource to request. This should be an
absolute URI but some implementations may support relative URIs
(with absolute or relative paths). I{HTTP} and I{HTTPS} are the
schemes most likely to be supported but others may be as well.
@type uri: L{bytes}
@param headers: The headers to send with the request (or L{None} to
send no extra headers). An implementation may add its own headers
to this (for example for client identification or content
negotiation).
@type headers: L{Headers} or L{None}
@param bodyProducer: An object which can generate bytes to make up the
body of this request (for example, the properly encoded contents of
a file for a file upload). Or, L{None} if the request is to have
no body.
@type bodyProducer: L{IBodyProducer} provider
@return: A L{Deferred} that fires with an L{IResponse} provider when
the header of the response has been received (regardless of the
response status code) or with a L{Failure} if there is any problem
which prevents that response from being received (including
problems that prevent the request from being sent).
@rtype: L{Deferred}
""" | Request the resource at the given location.
@param method: The request method to use, such as C{"GET"}, C{"HEAD"},
C{"PUT"}, C{"POST"}, etc.
@type method: L{bytes}
@param uri: The location of the resource to request. This should be an
absolute URI but some implementations may support relative URIs
(with absolute or relative paths). I{HTTP} and I{HTTPS} are the
schemes most likely to be supported but others may be as well.
@type uri: L{bytes}
@param headers: The headers to send with the request (or L{None} to
send no extra headers). An implementation may add its own headers
to this (for example for client identification or content
negotiation).
@type headers: L{Headers} or L{None}
@param bodyProducer: An object which can generate bytes to make up the
body of this request (for example, the properly encoded contents of
a file for a file upload). Or, L{None} if the request is to have
no body.
@type bodyProducer: L{IBodyProducer} provider
@return: A L{Deferred} that fires with an L{IResponse} provider when
the header of the response has been received (regardless of the
response status code) or with a L{Failure} if there is any problem
which prevents that response from being received (including
problems that prevent the request from being sent).
@rtype: L{Deferred} | request | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def creatorForNetloc(hostname, port):
"""
Create a L{client connection creator
<twisted.internet.interfaces.IOpenSSLClientConnectionCreator>}
appropriate for the given URL "netloc"; i.e. hostname and port number
pair.
@param hostname: The name of the requested remote host.
@type hostname: L{bytes}
@param port: The number of the requested remote port.
@type port: L{int}
@return: A client connection creator expressing the security
requirements for the given remote host.
@rtype: L{client connection creator
<twisted.internet.interfaces.IOpenSSLClientConnectionCreator>}
""" | Create a L{client connection creator
<twisted.internet.interfaces.IOpenSSLClientConnectionCreator>}
appropriate for the given URL "netloc"; i.e. hostname and port number
pair.
@param hostname: The name of the requested remote host.
@type hostname: L{bytes}
@param port: The number of the requested remote port.
@type port: L{int}
@return: A client connection creator expressing the security
requirements for the given remote host.
@rtype: L{client connection creator
<twisted.internet.interfaces.IOpenSSLClientConnectionCreator>} | creatorForNetloc | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def endpointForURI(uri):
"""
Construct and return an L{IStreamClientEndpoint} for the outgoing
request's connection.
@param uri: The URI of the request.
@type uri: L{twisted.web.client.URI}
@return: An endpoint which will have its C{connect} method called to
issue the request.
@rtype: an L{IStreamClientEndpoint} provider
@raises twisted.internet.error.SchemeNotSupported: If the given
URI's scheme cannot be handled by this factory.
""" | Construct and return an L{IStreamClientEndpoint} for the outgoing
request's connection.
@param uri: The URI of the request.
@type uri: L{twisted.web.client.URI}
@return: An endpoint which will have its C{connect} method called to
issue the request.
@rtype: an L{IStreamClientEndpoint} provider
@raises twisted.internet.error.SchemeNotSupported: If the given
URI's scheme cannot be handled by this factory. | endpointForURI | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/iweb.py | MIT |
def _callAppFunction(function):
"""
Call C{function}. If it raises an exception, log it with a minimal
description of the source.
@return: L{None}
"""
try:
function()
except:
_moduleLog.failure(
u"Unexpected exception from {name}",
name=fullyQualifiedName(function)
) | Call C{function}. If it raises an exception, log it with a minimal
description of the source.
@return: L{None} | _callAppFunction | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def switchToBodyMode(self, decoder):
"""
Switch to body parsing mode - interpret any more bytes delivered as
part of the message body and deliver them to the given decoder.
"""
if self.state == BODY:
raise RuntimeError(u"already in body mode")
self.bodyDecoder = decoder
self.state = BODY
self.setRawMode() | Switch to body parsing mode - interpret any more bytes delivered as
part of the message body and deliver them to the given decoder. | switchToBodyMode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def lineReceived(self, line):
"""
Handle one line from a response.
"""
# Handle the normal CR LF case.
if line[-1:] == b'\r':
line = line[:-1]
if self.state == STATUS:
self.statusReceived(line)
self.state = HEADER
elif self.state == HEADER:
if not line or line[0] not in b' \t':
if self._partialHeader is not None:
header = b''.join(self._partialHeader)
name, value = header.split(b':', 1)
value = value.strip()
self.headerReceived(name, value)
if not line:
# Empty line means the header section is over.
self.allHeadersReceived()
else:
# Line not beginning with LWS is another header.
self._partialHeader = [line]
else:
# A line beginning with LWS is a continuation of a header
# begun on a previous line.
self._partialHeader.append(line) | Handle one line from a response. | lineReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def rawDataReceived(self, data):
"""
Pass data from the message body to the body decoder object.
"""
self.bodyDecoder.dataReceived(data) | Pass data from the message body to the body decoder object. | rawDataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def isConnectionControlHeader(self, name):
"""
Return C{True} if the given lower-cased name is the name of a
connection control header (rather than an entity header).
According to RFC 2616, section 14.10, the tokens in the Connection
header are probably relevant here. However, I am not sure what the
practical consequences of either implementing or ignoring that are.
So I leave it unimplemented for the time being.
"""
return name in self.CONNECTION_CONTROL_HEADERS | Return C{True} if the given lower-cased name is the name of a
connection control header (rather than an entity header).
According to RFC 2616, section 14.10, the tokens in the Connection
header are probably relevant here. However, I am not sure what the
practical consequences of either implementing or ignoring that are.
So I leave it unimplemented for the time being. | isConnectionControlHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def statusReceived(self, status):
"""
Callback invoked whenever the first line of a new message is received.
Override this.
@param status: The first line of an HTTP request or response message
without trailing I{CR LF}.
@type status: C{bytes}
""" | Callback invoked whenever the first line of a new message is received.
Override this.
@param status: The first line of an HTTP request or response message
without trailing I{CR LF}.
@type status: C{bytes} | statusReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def headerReceived(self, name, value):
"""
Store the given header in C{self.headers}.
"""
name = name.lower()
if self.isConnectionControlHeader(name):
headers = self.connHeaders
else:
headers = self.headers
headers.addRawHeader(name, value) | Store the given header in C{self.headers}. | headerReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def allHeadersReceived(self):
"""
Callback invoked after the last header is passed to C{headerReceived}.
Override this to change to the C{BODY} or C{DONE} state.
"""
self.switchToBodyMode(None) | Callback invoked after the last header is passed to C{headerReceived}.
Override this to change to the C{BODY} or C{DONE} state. | allHeadersReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def dataReceived(self, data):
"""
Override so that we know if any response has been received.
"""
self._everReceivedData = True
HTTPParser.dataReceived(self, data) | Override so that we know if any response has been received. | dataReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def parseVersion(self, strversion):
"""
Parse version strings of the form Protocol '/' Major '.' Minor. E.g.
b'HTTP/1.1'. Returns (protocol, major, minor). Will raise ValueError
on bad syntax.
"""
try:
proto, strnumber = strversion.split(b'/')
major, minor = strnumber.split(b'.')
major, minor = int(major), int(minor)
except ValueError as e:
raise BadResponseVersion(str(e), strversion)
if major < 0 or minor < 0:
raise BadResponseVersion(u"version may not be negative",
strversion)
return (proto, major, minor) | Parse version strings of the form Protocol '/' Major '.' Minor. E.g.
b'HTTP/1.1'. Returns (protocol, major, minor). Will raise ValueError
on bad syntax. | parseVersion | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def statusReceived(self, status):
"""
Parse the status line into its components and create a response object
to keep track of this response's state.
"""
parts = status.split(b' ', 2)
if len(parts) == 2:
# Some broken servers omit the required `phrase` portion of
# `status-line`. One such server identified as
# "cloudflare-nginx". Others fail to identify themselves
# entirely. Fill in an empty phrase for such cases.
version, codeBytes = parts
phrase = b""
elif len(parts) == 3:
version, codeBytes, phrase = parts
else:
raise ParseError(u"wrong number of parts", status)
try:
statusCode = int(codeBytes)
except ValueError:
raise ParseError(u"non-integer status code", status)
self.response = Response._construct(
self.parseVersion(version),
statusCode,
phrase,
self.headers,
self.transport,
self.request,
) | Parse the status line into its components and create a response object
to keep track of this response's state. | statusReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def _finished(self, rest):
"""
Called to indicate that an entire response has been received. No more
bytes will be interpreted by this L{HTTPClientParser}. Extra bytes are
passed up and the state of this L{HTTPClientParser} is set to I{DONE}.
@param rest: A C{bytes} giving any extra bytes delivered to this
L{HTTPClientParser} which are not part of the response being
parsed.
"""
self.state = DONE
self.finisher(rest) | Called to indicate that an entire response has been received. No more
bytes will be interpreted by this L{HTTPClientParser}. Extra bytes are
passed up and the state of this L{HTTPClientParser} is set to I{DONE}.
@param rest: A C{bytes} giving any extra bytes delivered to this
L{HTTPClientParser} which are not part of the response being
parsed. | _finished | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def isConnectionControlHeader(self, name):
"""
Content-Length in the response to a HEAD request is an entity header,
not a connection control header.
"""
if self.request.method == b'HEAD' and name == b'content-length':
return False
return HTTPParser.isConnectionControlHeader(self, name) | Content-Length in the response to a HEAD request is an entity header,
not a connection control header. | isConnectionControlHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def allHeadersReceived(self):
"""
Figure out how long the response body is going to be by examining
headers and stuff.
"""
if 100 <= self.response.code < 200:
# RFC 7231 Section 6.2 says that if we receive a 1XX status code
# and aren't expecting it, we MAY ignore it. That's what we're
# going to do. We reset the parser here, but we leave
# _everReceivedData in its True state because we have, in fact,
# received data.
self._log.info(
"Ignoring unexpected {code} response",
code=self.response.code
)
self.connectionMade()
del self.response
return
if (self.response.code in self.NO_BODY_CODES
or self.request.method == b'HEAD'):
self.response.length = 0
# The order of the next two lines might be of interest when adding
# support for pipelining.
self._finished(self.clearLineBuffer())
self.response._bodyDataFinished()
else:
transferEncodingHeaders = self.connHeaders.getRawHeaders(
b'transfer-encoding')
if transferEncodingHeaders:
# This could be a KeyError. However, that would mean we do not
# know how to decode the response body, so failing the request
# is as good a behavior as any. Perhaps someday we will want
# to normalize/document/test this specifically, but failing
# seems fine to me for now.
transferDecoder = self._transferDecoders[transferEncodingHeaders[0].lower()]
# If anyone ever invents a transfer encoding other than
# chunked (yea right), and that transfer encoding can predict
# the length of the response body, it might be sensible to
# allow the transfer decoder to set the response object's
# length attribute.
else:
contentLengthHeaders = self.connHeaders.getRawHeaders(
b'content-length')
if contentLengthHeaders is None:
contentLength = None
elif len(contentLengthHeaders) == 1:
contentLength = int(contentLengthHeaders[0])
self.response.length = contentLength
else:
# "HTTP Message Splitting" or "HTTP Response Smuggling"
# potentially happening. Or it's just a buggy server.
raise ValueError(u"Too many Content-Length headers; "
u"response is invalid")
if contentLength == 0:
self._finished(self.clearLineBuffer())
transferDecoder = None
else:
transferDecoder = lambda x, y: _IdentityTransferDecoder(
contentLength, x, y)
if transferDecoder is None:
self.response._bodyDataFinished()
else:
# Make sure as little data as possible from the response body
# gets delivered to the response object until the response
# object actually indicates it is ready to handle bytes
# (probably because an application gave it a way to interpret
# them).
self.transport.pauseProducing()
self.switchToBodyMode(transferDecoder(
self.response._bodyDataReceived,
self._finished))
# This must be last. If it were first, then application code might
# change some state (for example, registering a protocol to receive the
# response body). Then the pauseProducing above would be wrong since
# the response is ready for bytes and nothing else would ever resume
# the transport.
self._responseDeferred.callback(self.response)
del self._responseDeferred | Figure out how long the response body is going to be by examining
headers and stuff. | allHeadersReceived | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def _ensureValidMethod(method):
"""
An HTTP method is an HTTP token, which consists of any visible
ASCII character that is not a delimiter (i.e. one of
C{"(),/:;<=>?@[\\]{}}.)
@param method: the method to check
@type method: L{bytes}
@return: the method if it is valid
@rtype: L{bytes}
@raise ValueError: if the method is not valid
@see: U{https://tools.ietf.org/html/rfc7230#section-3.1.1},
U{https://tools.ietf.org/html/rfc7230#section-3.2.6},
U{https://tools.ietf.org/html/rfc5234#appendix-B.1}
"""
if _VALID_METHOD.match(method):
return method
raise ValueError("Invalid method {!r}".format(method)) | An HTTP method is an HTTP token, which consists of any visible
ASCII character that is not a delimiter (i.e. one of
C{"(),/:;<=>?@[\\]{}}.)
@param method: the method to check
@type method: L{bytes}
@return: the method if it is valid
@rtype: L{bytes}
@raise ValueError: if the method is not valid
@see: U{https://tools.ietf.org/html/rfc7230#section-3.1.1},
U{https://tools.ietf.org/html/rfc7230#section-3.2.6},
U{https://tools.ietf.org/html/rfc5234#appendix-B.1} | _ensureValidMethod | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def _ensureValidURI(uri):
"""
A valid URI cannot contain control characters (i.e., characters
between 0-32, inclusive and 127) or non-ASCII characters (i.e.,
characters with values between 128-255, inclusive).
@param uri: the URI to check
@type uri: L{bytes}
@return: the URI if it is valid
@rtype: L{bytes}
@raise ValueError: if the URI is not valid
@see: U{https://tools.ietf.org/html/rfc3986#section-3.3},
U{https://tools.ietf.org/html/rfc3986#appendix-A},
U{https://tools.ietf.org/html/rfc5234#appendix-B.1}
"""
if _VALID_URI.match(uri):
return uri
raise ValueError("Invalid URI {!r}".format(uri)) | A valid URI cannot contain control characters (i.e., characters
between 0-32, inclusive and 127) or non-ASCII characters (i.e.,
characters with values between 128-255, inclusive).
@param uri: the URI to check
@type uri: L{bytes}
@return: the URI if it is valid
@rtype: L{bytes}
@raise ValueError: if the URI is not valid
@see: U{https://tools.ietf.org/html/rfc3986#section-3.3},
U{https://tools.ietf.org/html/rfc3986#appendix-A},
U{https://tools.ietf.org/html/rfc5234#appendix-B.1} | _ensureValidURI | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def __init__(self, method, uri, headers, bodyProducer, persistent=False):
"""
@param method: The HTTP method for this request, ex: b'GET', b'HEAD',
b'POST', etc.
@type method: L{bytes}
@param uri: The relative URI of the resource to request. For example,
C{b'/foo/bar?baz=quux'}.
@type uri: L{bytes}
@param headers: Headers to be sent to the server. It is important to
note that this object does not create any implicit headers. So it
is up to the HTTP Client to add required headers such as 'Host'.
@type headers: L{twisted.web.http_headers.Headers}
@param bodyProducer: L{None} or an L{IBodyProducer} provider which
produces the content body to send to the remote HTTP server.
@param persistent: Set to C{True} when you use HTTP persistent
connection, defaults to C{False}.
@type persistent: L{bool}
"""
self.method = _ensureValidMethod(method)
self.uri = _ensureValidURI(uri)
self.headers = headers
self.bodyProducer = bodyProducer
self.persistent = persistent
self._parsedURI = None | @param method: The HTTP method for this request, ex: b'GET', b'HEAD',
b'POST', etc.
@type method: L{bytes}
@param uri: The relative URI of the resource to request. For example,
C{b'/foo/bar?baz=quux'}.
@type uri: L{bytes}
@param headers: Headers to be sent to the server. It is important to
note that this object does not create any implicit headers. So it
is up to the HTTP Client to add required headers such as 'Host'.
@type headers: L{twisted.web.http_headers.Headers}
@param bodyProducer: L{None} or an L{IBodyProducer} provider which
produces the content body to send to the remote HTTP server.
@param persistent: Set to C{True} when you use HTTP persistent
connection, defaults to C{False}.
@type persistent: L{bool} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def _construct(cls, method, uri, headers, bodyProducer, persistent=False,
parsedURI=None):
"""
Private constructor.
@param method: See L{__init__}.
@param uri: See L{__init__}.
@param headers: See L{__init__}.
@param bodyProducer: See L{__init__}.
@param persistent: See L{__init__}.
@param parsedURI: See L{Request._parsedURI}.
@return: L{Request} instance.
"""
request = cls(method, uri, headers, bodyProducer, persistent)
request._parsedURI = parsedURI
return request | Private constructor.
@param method: See L{__init__}.
@param uri: See L{__init__}.
@param headers: See L{__init__}.
@param bodyProducer: See L{__init__}.
@param persistent: See L{__init__}.
@param parsedURI: See L{Request._parsedURI}.
@return: L{Request} instance. | _construct | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def absoluteURI(self):
"""
The absolute URI of the request as C{bytes}, or L{None} if the
absolute URI cannot be determined.
"""
return getattr(self._parsedURI, 'toBytes', lambda: None)() | The absolute URI of the request as C{bytes}, or L{None} if the
absolute URI cannot be determined. | absoluteURI | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def _writeToBodyProducerChunked(self, transport):
"""
Write this request to the given transport using chunked
transfer-encoding to frame the body.
@param transport: See L{writeTo}.
@return: See L{writeTo}.
"""
self._writeHeaders(transport, b'Transfer-Encoding: chunked\r\n')
encoder = ChunkedEncoder(transport)
encoder.registerProducer(self.bodyProducer, True)
d = self.bodyProducer.startProducing(encoder)
def cbProduced(ignored):
encoder.unregisterProducer()
def ebProduced(err):
encoder._allowNoMoreWrites()
# Don't call the encoder's unregisterProducer because it will write
# a zero-length chunk. This would indicate to the server that the
# request body is complete. There was an error, though, so we
# don't want to do that.
transport.unregisterProducer()
return err
d.addCallbacks(cbProduced, ebProduced)
return d | Write this request to the given transport using chunked
transfer-encoding to frame the body.
@param transport: See L{writeTo}.
@return: See L{writeTo}. | _writeToBodyProducerChunked | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def _writeToBodyProducerContentLength(self, transport):
"""
Write this request to the given transport using content-length to frame
the body.
@param transport: See L{writeTo}.
@return: See L{writeTo}.
"""
self._writeHeaders(
transport,
networkString(
'Content-Length: %d\r\n' % (self.bodyProducer.length,)))
# This Deferred is used to signal an error in the data written to the
# encoder below. It can only errback and it will only do so before too
# many bytes have been written to the encoder and before the producer
# Deferred fires.
finishedConsuming = Deferred()
# This makes sure the producer writes the correct number of bytes for
# the request body.
encoder = LengthEnforcingConsumer(
self.bodyProducer, transport, finishedConsuming)
transport.registerProducer(self.bodyProducer, True)
finishedProducing = self.bodyProducer.startProducing(encoder)
def combine(consuming, producing):
# This Deferred is returned and will be fired when the first of
# consuming or producing fires. If it's cancelled, forward that
# cancellation to the producer.
def cancelConsuming(ign):
finishedProducing.cancel()
ultimate = Deferred(cancelConsuming)
# Keep track of what has happened so far. This initially
# contains None, then an integer uniquely identifying what
# sequence of events happened. See the callbacks and errbacks
# defined below for the meaning of each value.
state = [None]
def ebConsuming(err):
if state == [None]:
# The consuming Deferred failed first. This means the
# overall writeTo Deferred is going to errback now. The
# producing Deferred should not fire later (because the
# consumer should have called stopProducing on the
# producer), but if it does, a callback will be ignored
# and an errback will be logged.
state[0] = 1
ultimate.errback(err)
else:
# The consuming Deferred errbacked after the producing
# Deferred fired. This really shouldn't ever happen.
# If it does, I goofed. Log the error anyway, just so
# there's a chance someone might notice and complain.
self._log.failure(
u"Buggy state machine in {request}/[{state}]: "
u"ebConsuming called",
failure=err,
request=repr(self),
state=state[0]
)
def cbProducing(result):
if state == [None]:
# The producing Deferred succeeded first. Nothing will
# ever happen to the consuming Deferred. Tell the
# encoder we're done so it can check what the producer
# wrote and make sure it was right.
state[0] = 2
try:
encoder._noMoreWritesExpected()
except:
# Fail the overall writeTo Deferred - something the
# producer did was wrong.
ultimate.errback()
else:
# Success - succeed the overall writeTo Deferred.
ultimate.callback(None)
# Otherwise, the consuming Deferred already errbacked. The
# producing Deferred wasn't supposed to fire, but it did
# anyway. It's buggy, but there's not really anything to be
# done about it. Just ignore this result.
def ebProducing(err):
if state == [None]:
# The producing Deferred failed first. This means the
# overall writeTo Deferred is going to errback now.
# Tell the encoder that we're done so it knows to reject
# further writes from the producer (which should not
# happen, but the producer may be buggy).
state[0] = 3
encoder._allowNoMoreWrites()
ultimate.errback(err)
else:
# The producing Deferred failed after the consuming
# Deferred failed. It shouldn't have, so it's buggy.
# Log the exception in case anyone who can fix the code
# is watching.
self._log.failure(u"Producer is buggy", failure=err)
consuming.addErrback(ebConsuming)
producing.addCallbacks(cbProducing, ebProducing)
return ultimate
d = combine(finishedConsuming, finishedProducing)
def f(passthrough):
# Regardless of what happens with the overall Deferred, once it
# fires, the producer registered way up above the definition of
# combine should be unregistered.
transport.unregisterProducer()
return passthrough
d.addBoth(f)
return d | Write this request to the given transport using content-length to frame
the body.
@param transport: See L{writeTo}.
@return: See L{writeTo}. | _writeToBodyProducerContentLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def _writeToEmptyBodyContentLength(self, transport):
"""
Write this request to the given transport using content-length to frame
the (empty) body.
@param transport: See L{writeTo}.
@return: See L{writeTo}.
"""
self._writeHeaders(transport, b"Content-Length: 0\r\n")
return succeed(None) | Write this request to the given transport using content-length to frame
the (empty) body.
@param transport: See L{writeTo}.
@return: See L{writeTo}. | _writeToEmptyBodyContentLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def writeTo(self, transport):
"""
Format this L{Request} as an HTTP/1.1 request and write it to the given
transport. If bodyProducer is not None, it will be associated with an
L{IConsumer}.
@param transport: The transport to which to write.
@type transport: L{twisted.internet.interfaces.ITransport} provider
@return: A L{Deferred} which fires with L{None} when the request has
been completely written to the transport or with a L{Failure} if
there is any problem generating the request bytes.
"""
if self.bodyProducer is None:
# If the method semantics anticipate a body, include a
# Content-Length even if it is 0.
# https://tools.ietf.org/html/rfc7230#section-3.3.2
if self.method in (b"PUT", b"POST"):
self._writeToEmptyBodyContentLength(transport)
else:
self._writeHeaders(transport, None)
elif self.bodyProducer.length is UNKNOWN_LENGTH:
return self._writeToBodyProducerChunked(transport)
else:
return self._writeToBodyProducerContentLength(transport) | Format this L{Request} as an HTTP/1.1 request and write it to the given
transport. If bodyProducer is not None, it will be associated with an
L{IConsumer}.
@param transport: The transport to which to write.
@type transport: L{twisted.internet.interfaces.ITransport} provider
@return: A L{Deferred} which fires with L{None} when the request has
been completely written to the transport or with a L{Failure} if
there is any problem generating the request bytes. | writeTo | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | MIT |
def stopWriting(self):
"""
Stop writing this request to the transport. This can only be called
after C{writeTo} and before the L{Deferred} returned by C{writeTo}
fires. It should cancel any asynchronous task started by C{writeTo}.
The L{Deferred} returned by C{writeTo} need not be fired if this method
is called.
"""
# If bodyProducer is None, then the Deferred returned by writeTo has
# fired already and this method cannot be called.
_callAppFunction(self.bodyProducer.stopProducing) | Stop writing this request to the transport. This can only be called
after C{writeTo} and before the L{Deferred} returned by C{writeTo}
fires. It should cancel any asynchronous task started by C{writeTo}.
The L{Deferred} returned by C{writeTo} need not be fired if this method
is called. | stopWriting | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_newclient.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.