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 _allowNoMoreWrites(self): """ Indicate that no additional writes are allowed. Attempts to write after calling this method will be met with an exception. """ self._finished = None
Indicate that no additional writes are allowed. Attempts to write after calling this method will be met with an exception.
_allowNoMoreWrites
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 write(self, bytes): """ Write C{bytes} to the underlying consumer unless C{_noMoreWritesExpected} has been called or there are/have been too many bytes. """ if self._finished is None: # No writes are supposed to happen any more. Try to convince the # calling code to stop calling this method by calling its # stopProducing method and then throwing an exception at it. This # exception isn't documented as part of the API because you're # never supposed to expect it: only buggy code will ever receive # it. self._producer.stopProducing() raise ExcessWrite() if len(bytes) <= self._length: self._length -= len(bytes) self._consumer.write(bytes) else: # No synchronous exception is raised in *this* error path because # we still have _finished which we can use to report the error to a # better place than the direct caller of this method (some # arbitrary application code). _callAppFunction(self._producer.stopProducing) self._finished.errback(WrongBodyLength(u"too many bytes written")) self._allowNoMoreWrites()
Write C{bytes} to the underlying consumer unless C{_noMoreWritesExpected} has been called or there are/have been too many bytes.
write
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 _noMoreWritesExpected(self): """ Called to indicate no more bytes will be written to this consumer. Check to see that the correct number have been written. @raise WrongBodyLength: If not enough bytes have been written. """ if self._finished is not None: self._allowNoMoreWrites() if self._length: raise WrongBodyLength(u"too few bytes written")
Called to indicate no more bytes will be written to this consumer. Check to see that the correct number have been written. @raise WrongBodyLength: If not enough bytes have been written.
_noMoreWritesExpected
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 makeStatefulDispatcher(name, template): """ Given a I{dispatch} name and a function, return a function which can be used as a method and which, when called, will call another method defined on the instance and return the result. The other method which is called is determined by the value of the C{_state} attribute of the instance. @param name: A string which is used to construct the name of the subsidiary method to invoke. The subsidiary method is named like C{'_%s_%s' % (name, _state)}. @param template: A function object which is used to give the returned function a docstring. @return: The dispatcher function. """ def dispatcher(self, *args, **kwargs): func = getattr(self, '_' + name + '_' + self._state, None) if func is None: raise RuntimeError( u"%r has no %s method in state %s" % (self, name, self._state)) return func(*args, **kwargs) dispatcher.__doc__ = template.__doc__ return dispatcher
Given a I{dispatch} name and a function, return a function which can be used as a method and which, when called, will call another method defined on the instance and return the result. The other method which is called is determined by the value of the C{_state} attribute of the instance. @param name: A string which is used to construct the name of the subsidiary method to invoke. The subsidiary method is named like C{'_%s_%s' % (name, _state)}. @param template: A function object which is used to give the returned function a docstring. @return: The dispatcher function.
makeStatefulDispatcher
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, version, code, phrase, headers, _transport): """ @param version: HTTP version components protocol, major, minor. E.g. C{(b'HTTP', 1, 1)} to mean C{b'HTTP/1.1'}. @param code: HTTP status code. @type code: L{int} @param phrase: HTTP reason phrase, intended to give a short description of the HTTP status code. @param headers: HTTP response headers. @type headers: L{twisted.web.http_headers.Headers} @param _transport: The transport which is delivering this response. """ self.version = version self.code = code self.phrase = phrase self.headers = headers self._transport = _transport self._bodyBuffer = [] self._state = 'INITIAL' self.request = None self.previousResponse = None
@param version: HTTP version components protocol, major, minor. E.g. C{(b'HTTP', 1, 1)} to mean C{b'HTTP/1.1'}. @param code: HTTP status code. @type code: L{int} @param phrase: HTTP reason phrase, intended to give a short description of the HTTP status code. @param headers: HTTP response headers. @type headers: L{twisted.web.http_headers.Headers} @param _transport: The transport which is delivering this response.
__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, version, code, phrase, headers, _transport, request): """ Private constructor. @param version: See L{__init__}. @param code: See L{__init__}. @param phrase: See L{__init__}. @param headers: See L{__init__}. @param _transport: See L{__init__}. @param request: See L{IResponse.request}. @return: L{Response} instance. """ response = Response(version, code, phrase, headers, _transport) response.request = _ClientRequestProxy(request) return response
Private constructor. @param version: See L{__init__}. @param code: See L{__init__}. @param phrase: See L{__init__}. @param headers: See L{__init__}. @param _transport: See L{__init__}. @param request: See L{IResponse.request}. @return: L{Response} 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 deliverBody(self, protocol): """ Dispatch the given L{IProtocol} depending of the current state of the response. """
Dispatch the given L{IProtocol} depending of the current state of the response.
deliverBody
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 _deliverBody_INITIAL(self, protocol): """ Deliver any buffered data to C{protocol} and prepare to deliver any future data to it. Move to the C{'CONNECTED'} state. """ protocol.makeConnection(self._transport) self._bodyProtocol = protocol for data in self._bodyBuffer: self._bodyProtocol.dataReceived(data) self._bodyBuffer = None self._state = 'CONNECTED' # Now that there's a protocol to consume the body, resume the # transport. It was previously paused by HTTPClientParser to avoid # reading too much data before it could be handled. We need to do this # after we transition our state as it may recursively lead to more data # being delivered, or even the body completing. self._transport.resumeProducing()
Deliver any buffered data to C{protocol} and prepare to deliver any future data to it. Move to the C{'CONNECTED'} state.
_deliverBody_INITIAL
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 _deliverBody_CONNECTED(self, protocol): """ It is invalid to attempt to deliver data to a protocol when it is already being delivered to another protocol. """ raise RuntimeError( u"Response already has protocol %r, cannot deliverBody " u"again" % (self._bodyProtocol,))
It is invalid to attempt to deliver data to a protocol when it is already being delivered to another protocol.
_deliverBody_CONNECTED
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 _deliverBody_DEFERRED_CLOSE(self, protocol): """ Deliver any buffered data to C{protocol} and then disconnect the protocol. Move to the C{'FINISHED'} state. """ # Unlike _deliverBody_INITIAL, there is no need to resume the # transport here because all of the response data has been received # already. Some higher level code may want to resume the transport if # that code expects further data to be received over it. protocol.makeConnection(self._transport) for data in self._bodyBuffer: protocol.dataReceived(data) self._bodyBuffer = None protocol.connectionLost(self._reason) self._state = 'FINISHED'
Deliver any buffered data to C{protocol} and then disconnect the protocol. Move to the C{'FINISHED'} state.
_deliverBody_DEFERRED_CLOSE
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 _deliverBody_FINISHED(self, protocol): """ It is invalid to attempt to deliver data to a protocol after the response body has been delivered to another protocol. """ raise RuntimeError( u"Response already finished, cannot deliverBody now.")
It is invalid to attempt to deliver data to a protocol after the response body has been delivered to another protocol.
_deliverBody_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 _bodyDataReceived(self, data): """ Called by HTTPClientParser with chunks of data from the response body. They will be buffered or delivered to the protocol passed to deliverBody. """
Called by HTTPClientParser with chunks of data from the response body. They will be buffered or delivered to the protocol passed to deliverBody.
_bodyDataReceived
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 _bodyDataReceived_INITIAL(self, data): """ Buffer any data received for later delivery to a protocol passed to C{deliverBody}. Little or no data should be buffered by this method, since the transport has been paused and will not be resumed until a protocol is supplied. """ self._bodyBuffer.append(data)
Buffer any data received for later delivery to a protocol passed to C{deliverBody}. Little or no data should be buffered by this method, since the transport has been paused and will not be resumed until a protocol is supplied.
_bodyDataReceived_INITIAL
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 _bodyDataReceived_CONNECTED(self, data): """ Deliver any data received to the protocol to which this L{Response} is connected. """ self._bodyProtocol.dataReceived(data)
Deliver any data received to the protocol to which this L{Response} is connected.
_bodyDataReceived_CONNECTED
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 _bodyDataReceived_DEFERRED_CLOSE(self, data): """ It is invalid for data to be delivered after it has been indicated that the response body has been completely delivered. """ raise RuntimeError(u"Cannot receive body data after _bodyDataFinished")
It is invalid for data to be delivered after it has been indicated that the response body has been completely delivered.
_bodyDataReceived_DEFERRED_CLOSE
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 _bodyDataReceived_FINISHED(self, data): """ It is invalid for data to be delivered after the response body has been delivered to a protocol. """ raise RuntimeError(u"Cannot receive body data after " u"protocol disconnected")
It is invalid for data to be delivered after the response body has been delivered to a protocol.
_bodyDataReceived_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 _bodyDataFinished(self, reason=None): """ Called by HTTPClientParser when no more body data is available. If the optional reason is supplied, this indicates a problem or potential problem receiving all of the response body. """
Called by HTTPClientParser when no more body data is available. If the optional reason is supplied, this indicates a problem or potential problem receiving all of the response body.
_bodyDataFinished
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 _bodyDataFinished_INITIAL(self, reason=None): """ Move to the C{'DEFERRED_CLOSE'} state to wait for a protocol to which to deliver the response body. """ self._state = 'DEFERRED_CLOSE' if reason is None: reason = Failure(ResponseDone(u"Response body fully received")) self._reason = reason
Move to the C{'DEFERRED_CLOSE'} state to wait for a protocol to which to deliver the response body.
_bodyDataFinished_INITIAL
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 _bodyDataFinished_CONNECTED(self, reason=None): """ Disconnect the protocol and move to the C{'FINISHED'} state. """ if reason is None: reason = Failure(ResponseDone(u"Response body fully received")) self._bodyProtocol.connectionLost(reason) self._bodyProtocol = None self._state = 'FINISHED'
Disconnect the protocol and move to the C{'FINISHED'} state.
_bodyDataFinished_CONNECTED
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 _bodyDataFinished_DEFERRED_CLOSE(self): """ It is invalid to attempt to notify the L{Response} of the end of the response body data more than once. """ raise RuntimeError(u"Cannot finish body data more than once")
It is invalid to attempt to notify the L{Response} of the end of the response body data more than once.
_bodyDataFinished_DEFERRED_CLOSE
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 _bodyDataFinished_FINISHED(self): """ It is invalid to attempt to notify the L{Response} of the end of the response body data more than once. """ raise RuntimeError(u"Cannot finish body data after " u"protocol disconnected")
It is invalid to attempt to notify the L{Response} of the end of the response body data more than once.
_bodyDataFinished_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 _allowNoMoreWrites(self): """ Indicate that no additional writes are allowed. Attempts to write after calling this method will be met with an exception. """ self.transport = None
Indicate that no additional writes are allowed. Attempts to write after calling this method will be met with an exception.
_allowNoMoreWrites
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 registerProducer(self, producer, streaming): """ Register the given producer with C{self.transport}. """ self.transport.registerProducer(producer, streaming)
Register the given producer with C{self.transport}.
registerProducer
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 write(self, data): """ Write the given request body bytes to the transport using chunked encoding. @type data: C{bytes} """ if self.transport is None: raise ExcessWrite() self.transport.writeSequence((networkString("%x\r\n" % len(data)), data, b"\r\n"))
Write the given request body bytes to the transport using chunked encoding. @type data: C{bytes}
write
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 unregisterProducer(self): """ Indicate that the request body is complete and finish the request. """ self.write(b'') self.transport.unregisterProducer() self._allowNoMoreWrites()
Indicate that the request body is complete and finish the request.
unregisterProducer
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 stopProxying(self): """ Stop forwarding calls of L{twisted.internet.interfaces.IPushProducer} methods to the underlying L{twisted.internet.interfaces.IPushProducer} provider. """ self._producer = None
Stop forwarding calls of L{twisted.internet.interfaces.IPushProducer} methods to the underlying L{twisted.internet.interfaces.IPushProducer} provider.
stopProxying
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 stopProducing(self): """ Proxy the stoppage to the underlying producer, unless this proxy has been stopped. """ if self._producer is not None: self._producer.stopProducing()
Proxy the stoppage to the underlying producer, unless this proxy has been stopped.
stopProducing
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 resumeProducing(self): """ Proxy the resumption to the underlying producer, unless this proxy has been stopped. """ if self._producer is not None: self._producer.resumeProducing()
Proxy the resumption to the underlying producer, unless this proxy has been stopped.
resumeProducing
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 pauseProducing(self): """ Proxy the pause to the underlying producer, unless this proxy has been stopped. """ if self._producer is not None: self._producer.pauseProducing()
Proxy the pause to the underlying producer, unless this proxy has been stopped.
pauseProducing
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 loseConnection(self): """ Proxy the request to lose the connection to the underlying producer, unless this proxy has been stopped. """ if self._producer is not None: self._producer.loseConnection()
Proxy the request to lose the connection to the underlying producer, unless this proxy has been stopped.
loseConnection
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 request(self, request): """ Issue C{request} over C{self.transport} and return a L{Deferred} which will fire with a L{Response} instance or an error. @param request: The object defining the parameters of the request to issue. @type request: L{Request} @rtype: L{Deferred} @return: The deferred may errback with L{RequestGenerationFailed} if the request was not fully written to the transport due to a local error. It may errback with L{RequestTransmissionFailed} if it was not fully written to the transport due to a network error. It may errback with L{ResponseFailed} if the request was sent (not necessarily received) but some or all of the response was lost. It may errback with L{RequestNotSent} if it is not possible to send any more requests using this L{HTTP11ClientProtocol}. """ if self._state != 'QUIESCENT': return fail(RequestNotSent()) self._state = 'TRANSMITTING' _requestDeferred = maybeDeferred(request.writeTo, self.transport) def cancelRequest(ign): # Explicitly cancel the request's deferred if it's still trying to # write when this request is cancelled. if self._state in ( 'TRANSMITTING', 'TRANSMITTING_AFTER_RECEIVING_RESPONSE'): _requestDeferred.cancel() else: self.transport.abortConnection() self._disconnectParser(Failure(CancelledError())) self._finishedRequest = Deferred(cancelRequest) # Keep track of the Request object in case we need to call stopWriting # on it. self._currentRequest = request self._transportProxy = TransportProxyProducer(self.transport) self._parser = HTTPClientParser(request, self._finishResponse) self._parser.makeConnection(self._transportProxy) self._responseDeferred = self._parser._responseDeferred def cbRequestWritten(ignored): if self._state == 'TRANSMITTING': self._state = 'WAITING' self._responseDeferred.chainDeferred(self._finishedRequest) def ebRequestWriting(err): if self._state == 'TRANSMITTING': self._state = 'GENERATION_FAILED' self.transport.abortConnection() self._finishedRequest.errback( Failure(RequestGenerationFailed([err]))) else: self._log.failure( u'Error writing request, but not in valid state ' u'to finalize request: {state}', failure=err, state=self._state ) _requestDeferred.addCallbacks(cbRequestWritten, ebRequestWriting) return self._finishedRequest
Issue C{request} over C{self.transport} and return a L{Deferred} which will fire with a L{Response} instance or an error. @param request: The object defining the parameters of the request to issue. @type request: L{Request} @rtype: L{Deferred} @return: The deferred may errback with L{RequestGenerationFailed} if the request was not fully written to the transport due to a local error. It may errback with L{RequestTransmissionFailed} if it was not fully written to the transport due to a network error. It may errback with L{ResponseFailed} if the request was sent (not necessarily received) but some or all of the response was lost. It may errback with L{RequestNotSent} if it is not possible to send any more requests using this L{HTTP11ClientProtocol}.
request
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 _finishResponse(self, rest): """ Called by an L{HTTPClientParser} to indicate that it has parsed a complete response. @param rest: A C{bytes} giving any trailing bytes which were given to the L{HTTPClientParser} which were not part of the response it was parsing. """
Called by an L{HTTPClientParser} to indicate that it has parsed a complete response. @param rest: A C{bytes} giving any trailing bytes which were given to the L{HTTPClientParser} which were not part of the response it was parsing.
_finishResponse
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 _disconnectParser(self, reason): """ If there is still a parser, call its C{connectionLost} method with the given reason. If there is not, do nothing. @type reason: L{Failure} """ if self._parser is not None: parser = self._parser self._parser = None self._currentRequest = None self._finishedRequest = None self._responseDeferred = None # The parser is no longer allowed to do anything to the real # transport. Stop proxying from the parser's transport to the real # transport before telling the parser it's done so that it can't do # anything. self._transportProxy.stopProxying() self._transportProxy = None parser.connectionLost(reason)
If there is still a parser, call its C{connectionLost} method with the given reason. If there is not, do nothing. @type reason: L{Failure}
_disconnectParser
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 _giveUp(self, reason): """ Lose the underlying connection and disconnect the parser with the given L{Failure}. Use this method instead of calling the transport's loseConnection method directly otherwise random things will break. """ self.transport.loseConnection() self._disconnectParser(reason)
Lose the underlying connection and disconnect the parser with the given L{Failure}. Use this method instead of calling the transport's loseConnection method directly otherwise random things will break.
_giveUp
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, bytes): """ Handle some stuff from some place. """ try: self._parser.dataReceived(bytes) except: self._giveUp(Failure())
Handle some stuff from some place.
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 connectionLost(self, reason): """ The underlying transport went away. If appropriate, notify the parser object. """
The underlying transport went away. If appropriate, notify the parser object.
connectionLost
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 _connectionLost_QUIESCENT(self, reason): """ Nothing is currently happening. Move to the C{'CONNECTION_LOST'} state but otherwise do nothing. """ self._state = 'CONNECTION_LOST'
Nothing is currently happening. Move to the C{'CONNECTION_LOST'} state but otherwise do nothing.
_connectionLost_QUIESCENT
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 _connectionLost_GENERATION_FAILED(self, reason): """ The connection was in an inconsistent state. Move to the C{'CONNECTION_LOST'} state but otherwise do nothing. """ self._state = 'CONNECTION_LOST'
The connection was in an inconsistent state. Move to the C{'CONNECTION_LOST'} state but otherwise do nothing.
_connectionLost_GENERATION_FAILED
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 _connectionLost_TRANSMITTING(self, reason): """ Fail the L{Deferred} for the current request, notify the request object that it does not need to continue transmitting itself, and move to the C{'CONNECTION_LOST'} state. """ self._state = 'CONNECTION_LOST' self._finishedRequest.errback( Failure(RequestTransmissionFailed([reason]))) del self._finishedRequest # Tell the request that it should stop bothering now. self._currentRequest.stopWriting()
Fail the L{Deferred} for the current request, notify the request object that it does not need to continue transmitting itself, and move to the C{'CONNECTION_LOST'} state.
_connectionLost_TRANSMITTING
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 _connectionLost_TRANSMITTING_AFTER_RECEIVING_RESPONSE(self, reason): """ Move to the C{'CONNECTION_LOST'} state. """ self._state = 'CONNECTION_LOST'
Move to the C{'CONNECTION_LOST'} state.
_connectionLost_TRANSMITTING_AFTER_RECEIVING_RESPONSE
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 _connectionLost_WAITING(self, reason): """ Disconnect the response parser so that it can propagate the event as necessary (for example, to call an application protocol's C{connectionLost} method, or to fail a request L{Deferred}) and move to the C{'CONNECTION_LOST'} state. """ self._disconnectParser(reason) self._state = 'CONNECTION_LOST'
Disconnect the response parser so that it can propagate the event as necessary (for example, to call an application protocol's C{connectionLost} method, or to fail a request L{Deferred}) and move to the C{'CONNECTION_LOST'} state.
_connectionLost_WAITING
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 _connectionLost_ABORTING(self, reason): """ Disconnect the response parser with a L{ConnectionAborted} failure, and move to the C{'CONNECTION_LOST'} state. """ self._disconnectParser(Failure(ConnectionAborted())) self._state = 'CONNECTION_LOST' for d in self._abortDeferreds: d.callback(None) self._abortDeferreds = []
Disconnect the response parser with a L{ConnectionAborted} failure, and move to the C{'CONNECTION_LOST'} state.
_connectionLost_ABORTING
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 abort(self): """ Close the connection and cause all outstanding L{request} L{Deferred}s to fire with an error. """ if self._state == "CONNECTION_LOST": return succeed(None) self.transport.loseConnection() self._state = 'ABORTING' d = Deferred() self._abortDeferreds.append(d) return d
Close the connection and cause all outstanding L{request} L{Deferred}s to fire with an error.
abort
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 urlparse(url): """ Parse an URL into six components. This is similar to C{urlparse.urlparse}, but rejects C{unicode} input and always produces C{bytes} output. @type url: C{bytes} @raise TypeError: The given url was a C{unicode} string instead of a C{bytes}. @return: The scheme, net location, path, params, query string, and fragment of the URL - all as C{bytes}. @rtype: C{ParseResultBytes} """ if isinstance(url, unicode): raise TypeError("url must be bytes, not unicode") scheme, netloc, path, params, query, fragment = _urlparse(url) if isinstance(scheme, unicode): scheme = scheme.encode('ascii') netloc = netloc.encode('ascii') path = path.encode('ascii') query = query.encode('ascii') fragment = fragment.encode('ascii') return ParseResultBytes(scheme, netloc, path, params, query, fragment)
Parse an URL into six components. This is similar to C{urlparse.urlparse}, but rejects C{unicode} input and always produces C{bytes} output. @type url: C{bytes} @raise TypeError: The given url was a C{unicode} string instead of a C{bytes}. @return: The scheme, net location, path, params, query string, and fragment of the URL - all as C{bytes}. @rtype: C{ParseResultBytes}
urlparse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def parse_qs(qs, keep_blank_values=0, strict_parsing=0): """ Like C{cgi.parse_qs}, but with support for parsing byte strings on Python 3. @type qs: C{bytes} """ d = {} items = [s2 for s1 in qs.split(b"&") for s2 in s1.split(b";")] for item in items: try: k, v = item.split(b"=", 1) except ValueError: if strict_parsing: raise continue if v or keep_blank_values: k = unquote(k.replace(b"+", b" ")) v = unquote(v.replace(b"+", b" ")) if k in d: d[k].append(v) else: d[k] = [v] return d
Like C{cgi.parse_qs}, but with support for parsing byte strings on Python 3. @type qs: C{bytes}
parse_qs
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def datetimeToString(msSinceEpoch=None): """ Convert seconds since epoch to HTTP datetime string. @rtype: C{bytes} """ if msSinceEpoch == None: msSinceEpoch = time.time() year, month, day, hh, mm, ss, wd, y, z = time.gmtime(msSinceEpoch) s = networkString("%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( weekdayname[wd], day, monthname[month], year, hh, mm, ss)) return s
Convert seconds since epoch to HTTP datetime string. @rtype: C{bytes}
datetimeToString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def datetimeToLogString(msSinceEpoch=None): """ Convert seconds since epoch to log datetime string. @rtype: C{str} """ if msSinceEpoch == None: msSinceEpoch = time.time() year, month, day, hh, mm, ss, wd, y, z = time.gmtime(msSinceEpoch) s = "[%02d/%3s/%4d:%02d:%02d:%02d +0000]" % ( day, monthname[month], year, hh, mm, ss) return s
Convert seconds since epoch to log datetime string. @rtype: C{str}
datetimeToLogString
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def timegm(year, month, day, hour, minute, second): """ Convert time tuple in GMT to seconds since epoch, GMT """ EPOCH = 1970 if year < EPOCH: raise ValueError("Years prior to %d not supported" % (EPOCH,)) assert 1 <= month <= 12 days = 365*(year-EPOCH) + calendar.leapdays(EPOCH, year) for i in range(1, month): days = days + calendar.mdays[i] if month > 2 and calendar.isleap(year): days = days + 1 days = days + day - 1 hours = days*24 + hour minutes = hours*60 + minute seconds = minutes*60 + second return seconds
Convert time tuple in GMT to seconds since epoch, GMT
timegm
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def stringToDatetime(dateString): """ Convert an HTTP date string (one of three formats) to seconds since epoch. @type dateString: C{bytes} """ parts = nativeString(dateString).split() if not parts[0][0:3].lower() in weekdayname_lower: # Weekday is stupid. Might have been omitted. try: return stringToDatetime(b"Sun, " + dateString) except ValueError: # Guess not. pass partlen = len(parts) if (partlen == 5 or partlen == 6) and parts[1].isdigit(): # 1st date format: Sun, 06 Nov 1994 08:49:37 GMT # (Note: "GMT" is literal, not a variable timezone) # (also handles without "GMT") # This is the normal format day = parts[1] month = parts[2] year = parts[3] time = parts[4] elif (partlen == 3 or partlen == 4) and parts[1].find('-') != -1: # 2nd date format: Sunday, 06-Nov-94 08:49:37 GMT # (Note: "GMT" is literal, not a variable timezone) # (also handles without without "GMT") # Two digit year, yucko. day, month, year = parts[1].split('-') time = parts[2] year=int(year) if year < 69: year = year + 2000 elif year < 100: year = year + 1900 elif len(parts) == 5: # 3rd date format: Sun Nov 6 08:49:37 1994 # ANSI C asctime() format. day = parts[2] month = parts[1] year = parts[4] time = parts[3] else: raise ValueError("Unknown datetime format %r" % dateString) day = int(day) month = int(monthname_lower.index(month.lower())) year = int(year) hour, min, sec = map(int, time.split(':')) return int(timegm(year, month, day, hour, min, sec))
Convert an HTTP date string (one of three formats) to seconds since epoch. @type dateString: C{bytes}
stringToDatetime
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def toChunk(data): """ Convert string to a chunk. @type data: C{bytes} @returns: a tuple of C{bytes} representing the chunked encoding of data """ return (networkString('%x' % (len(data),)), b"\r\n", data, b"\r\n")
Convert string to a chunk. @type data: C{bytes} @returns: a tuple of C{bytes} representing the chunked encoding of data
toChunk
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def fromChunk(data): """ Convert chunk to string. @type data: C{bytes} @return: tuple of (result, remaining) - both C{bytes}. @raise ValueError: If the given data is not a correctly formatted chunked byte string. """ prefix, rest = data.split(b'\r\n', 1) length = int(prefix, 16) if length < 0: raise ValueError("Chunk length must be >= 0, not %d" % (length,)) if rest[length:length + 2] != b'\r\n': raise ValueError("chunk must end with CRLF") return rest[:length], rest[length + 2:]
Convert chunk to string. @type data: C{bytes} @return: tuple of (result, remaining) - both C{bytes}. @raise ValueError: If the given data is not a correctly formatted chunked byte string.
fromChunk
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def parseContentRange(header): """ Parse a content-range header into (start, end, realLength). realLength might be None if real length is not known ('*'). """ kind, other = header.strip().split() if kind.lower() != "bytes": raise ValueError("a range of type %r is not supported") startend, realLength = other.split("/") start, end = map(int, startend.split("-")) if realLength == "*": realLength = None else: realLength = int(realLength) return (start, end, realLength)
Parse a content-range header into (start, end, realLength). realLength might be None if real length is not known ('*').
parseContentRange
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def connectionLost(reason): """ The underlying connection has been lost. @param reason: A failure instance indicating the reason why the connection was lost. @type reason: L{twisted.python.failure.Failure} """
The underlying connection has been lost. @param reason: A failure instance indicating the reason why the connection was lost. @type reason: L{twisted.python.failure.Failure}
connectionLost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def gotLength(length): """ Called when L{HTTPChannel} has determined the length, if any, of the incoming request's body. @param length: The length of the request's body. @type length: L{int} if the request declares its body's length and L{None} if it does not. """
Called when L{HTTPChannel} has determined the length, if any, of the incoming request's body. @param length: The length of the request's body. @type length: L{int} if the request declares its body's length and L{None} if it does not.
gotLength
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def handleContentChunk(data): """ Deliver a received chunk of body data to the request. Note this does not imply chunked transfer encoding. @param data: The received chunk. @type data: L{bytes} """
Deliver a received chunk of body data to the request. Note this does not imply chunked transfer encoding. @param data: The received chunk. @type data: L{bytes}
handleContentChunk
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def parseCookies(): """ Parse the request's cookies out of received headers. """
Parse the request's cookies out of received headers.
parseCookies
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def requestReceived(command, path, version): """ Called when the entire request, including its body, has been received. @param command: The request's HTTP command. @type command: L{bytes} @param path: The request's path. Note: this is actually what RFC7320 calls the URI. @type path: L{bytes} @param version: The request's HTTP version. @type version: L{bytes} """
Called when the entire request, including its body, has been received. @param command: The request's HTTP command. @type command: L{bytes} @param path: The request's path. Note: this is actually what RFC7320 calls the URI. @type path: L{bytes} @param version: The request's HTTP version. @type version: L{bytes}
requestReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def __eq__(other): """ Determines if two requests are the same object. @param other: Another object whose identity will be compared to this instance's. @return: L{True} when the two are the same object and L{False} when not. @rtype: L{bool} """
Determines if two requests are the same object. @param other: Another object whose identity will be compared to this instance's. @return: L{True} when the two are the same object and L{False} when not. @rtype: L{bool}
__eq__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def __ne__(other): """ Determines if two requests are not the same object. @param other: Another object whose identity will be compared to this instance's. @return: L{True} when the two are not the same object and L{False} when they are. @rtype: L{bool} """
Determines if two requests are not the same object. @param other: Another object whose identity will be compared to this instance's. @return: L{True} when the two are not the same object and L{False} when they are. @rtype: L{bool}
__ne__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def __hash__(): """ Generate a hash value for the request. @return: The request's hash value. @rtype: L{int} """
Generate a hash value for the request. @return: The request's hash value. @rtype: L{int}
__hash__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def extractHeader(self, header): """ Given a complete HTTP header, extract the field name and value and process the header. @param header: a complete HTTP request header of the form 'field-name: value'. @type header: C{bytes} """ key, val = header.split(b':', 1) val = val.lstrip() self.handleHeader(key, val) if key.lower() == b'content-length': self.length = int(val)
Given a complete HTTP header, extract the field name and value and process the header. @param header: a complete HTTP request header of the form 'field-name: value'. @type header: C{bytes}
extractHeader
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def lineReceived(self, line): """ Parse the status line and headers for an HTTP request. @param line: Part of an HTTP request header. Request bodies are parsed in L{HTTPClient.rawDataReceived}. @type line: C{bytes} """ if self.firstLine: self.firstLine = False l = line.split(None, 2) version = l[0] status = l[1] try: message = l[2] except IndexError: # sometimes there is no message message = b"" self.handleStatus(version, status, message) return if not line: if self._header != b"": # Only extract headers if there are any self.extractHeader(self._header) self.__buffer = StringIO() self.handleEndHeaders() self.setRawMode() return if line.startswith(b'\t') or line.startswith(b' '): # This line is part of a multiline header. According to RFC 822, in # "unfolding" multiline headers you do not strip the leading # whitespace on the continuing line. self._header = self._header + line elif self._header: # This line starts a new header, so process the previous one. self.extractHeader(self._header) self._header = line else: # First header self._header = line
Parse the status line and headers for an HTTP request. @param line: Part of an HTTP request header. Request bodies are parsed in L{HTTPClient.rawDataReceived}. @type line: C{bytes}
lineReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def handleResponseEnd(self): """ The response has been completely received. This callback may be invoked more than once per request. """ if self.__buffer is not None: b = self.__buffer.getvalue() self.__buffer = None self.handleResponse(b)
The response has been completely received. This callback may be invoked more than once per request.
handleResponseEnd
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def handleStatus(self, version, status, message): """ Called when the status-line is received. @param version: e.g. 'HTTP/1.0' @param status: e.g. '200' @type status: C{bytes} @param message: e.g. 'OK' """
Called when the status-line is received. @param version: e.g. 'HTTP/1.0' @param status: e.g. '200' @type status: C{bytes} @param message: e.g. 'OK'
handleStatus
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def handleHeader(self, key, val): """ Called every time a header is received. """
Called every time a header is received.
handleHeader
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def handleEndHeaders(self): """ Called when all headers have been received. """
Called when all headers have been received.
handleEndHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def __init__(self, channel, queued=_QUEUED_SENTINEL): """ @param channel: the channel we're connected to. @param queued: (deprecated) are we in the request queue, or can we start writing to the transport? """ self.notifications = [] self.channel = channel # Cache the client and server information, we'll need this # later to be serialized and sent with the request so CGIs # will work remotely self.client = self.channel.getPeer() self.host = self.channel.getHost() self.requestHeaders = Headers() self.received_cookies = {} self.responseHeaders = Headers() self.cookies = [] # outgoing cookies self.transport = self.channel.transport if queued is _QUEUED_SENTINEL: queued = False self.queued = queued
@param channel: the channel we're connected to. @param queued: (deprecated) are we in the request queue, or can we start writing to the transport?
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def _cleanup(self): """ Called when have finished responding and are no longer queued. """ if self.producer: self._log.failure( '', Failure( RuntimeError( "Producer was not unregistered for %s" % (self.uri,) ) ) ) self.unregisterProducer() self.channel.requestDone(self) del self.channel if self.content is not None: try: self.content.close() except OSError: # win32 suckiness, no idea why it does this pass del self.content for d in self.notifications: d.callback(None) self.notifications = []
Called when have finished responding and are no longer queued.
_cleanup
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def noLongerQueued(self): """ Notify the object that it is no longer queued. We start writing whatever data we have to the transport, etc. This method is not intended for users. In 16.3 this method was changed to become a no-op, as L{Request} objects are now never queued. """ pass
Notify the object that it is no longer queued. We start writing whatever data we have to the transport, etc. This method is not intended for users. In 16.3 this method was changed to become a no-op, as L{Request} objects are now never queued.
noLongerQueued
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def gotLength(self, length): """ Called when HTTP channel got length of content in this request. This method is not intended for users. @param length: The length of the request body, as indicated by the request headers. L{None} if the request headers do not indicate a length. """ if length is not None and length < 100000: self.content = StringIO() else: self.content = tempfile.TemporaryFile()
Called when HTTP channel got length of content in this request. This method is not intended for users. @param length: The length of the request body, as indicated by the request headers. L{None} if the request headers do not indicate a length.
gotLength
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def parseCookies(self): """ Parse cookie headers. This method is not intended for users. """ cookieheaders = self.requestHeaders.getRawHeaders(b"cookie") if cookieheaders is None: return for cookietxt in cookieheaders: if cookietxt: for cook in cookietxt.split(b';'): cook = cook.lstrip() try: k, v = cook.split(b'=', 1) self.received_cookies[k] = v except ValueError: pass
Parse cookie headers. This method is not intended for users.
parseCookies
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def handleContentChunk(self, data): """ Write a chunk of data. This method is not intended for users. """ self.content.write(data)
Write a chunk of data. This method is not intended for users.
handleContentChunk
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def requestReceived(self, command, path, version): """ Called by channel when all data has been received. This method is not intended for users. @type command: C{bytes} @param command: The HTTP verb of this request. This has the case supplied by the client (eg, it maybe "get" rather than "GET"). @type path: C{bytes} @param path: The URI of this request. @type version: C{bytes} @param version: The HTTP version of this request. """ self.content.seek(0,0) self.args = {} self.method, self.uri = command, path self.clientproto = version x = self.uri.split(b'?', 1) if len(x) == 1: self.path = self.uri else: self.path, argstring = x self.args = parse_qs(argstring, 1) # Argument processing args = self.args ctype = self.requestHeaders.getRawHeaders(b'content-type') clength = self.requestHeaders.getRawHeaders(b'content-length') if ctype is not None: ctype = ctype[0] if clength is not None: clength = clength[0] if self.method == b"POST" and ctype and clength: mfd = b'multipart/form-data' key, pdict = _parseHeader(ctype) pdict["CONTENT-LENGTH"] = clength if key == b'application/x-www-form-urlencoded': args.update(parse_qs(self.content.read(), 1)) elif key == mfd: try: if _PY37PLUS: cgiArgs = cgi.parse_multipart( self.content, pdict, encoding='utf8', errors="surrogateescape") else: cgiArgs = cgi.parse_multipart(self.content, pdict) if not _PY37PLUS and _PY3: # The parse_multipart function on Python 3 # decodes the header bytes as iso-8859-1 and # returns a str key -- we want bytes so encode # it back self.args.update({x.encode('iso-8859-1'): y for x, y in cgiArgs.items()}) elif _PY37PLUS: # The parse_multipart function on Python 3.7+ # decodes the header bytes as iso-8859-1 and # decodes the body bytes as utf8 with # surrogateescape -- we want bytes self.args.update({ x.encode('iso-8859-1'): \ [z.encode('utf8', "surrogateescape") if isinstance(z, str) else z for z in y] for x, y in cgiArgs.items()}) else: self.args.update(cgiArgs) except Exception as e: # It was a bad request, or we got a signal. self.channel._respondToBadRequestAndDisconnect() if isinstance(e, (TypeError, ValueError, KeyError)): return else: # If it's not a userspace error from CGI, reraise raise self.content.seek(0, 0) self.process()
Called by channel when all data has been received. This method is not intended for users. @type command: C{bytes} @param command: The HTTP verb of this request. This has the case supplied by the client (eg, it maybe "get" rather than "GET"). @type path: C{bytes} @param path: The URI of this request. @type version: C{bytes} @param version: The HTTP version of this request.
requestReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def __repr__(self): """ Return a string description of the request including such information as the request method and request URI. @return: A string loosely describing this L{Request} object. @rtype: L{str} """ return '<%s at 0x%x method=%s uri=%s clientproto=%s>' % ( self.__class__.__name__, id(self), nativeString(self.method), nativeString(self.uri), nativeString(self.clientproto))
Return a string description of the request including such information as the request method and request URI. @return: A string loosely describing this L{Request} object. @rtype: L{str}
__repr__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def process(self): """ Override in subclasses. This method is not intended for users. """ pass
Override in subclasses. This method is not intended for users.
process
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def registerProducer(self, producer, streaming): """ Register a producer. """ if self.producer: raise ValueError( "registering producer %s before previous one (%s) was " "unregistered" % (producer, self.producer)) self.streamingProducer = streaming self.producer = producer self.channel.registerProducer(producer, streaming)
Register a producer.
registerProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def unregisterProducer(self): """ Unregister the producer. """ self.channel.unregisterProducer() self.producer = None
Unregister the producer.
unregisterProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getHeader(self, key): """ Get an HTTP request header. @type key: C{bytes} or C{str} @param key: The name of the header to get the value of. @rtype: C{bytes} or C{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 L{key}. """ value = self.requestHeaders.getRawHeaders(key) if value is not None: return value[-1]
Get an HTTP request header. @type key: C{bytes} or C{str} @param key: The name of the header to get the value of. @rtype: C{bytes} or C{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 L{key}.
getHeader
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getCookie(self, key): """ Get a cookie that was sent from the network. @type key: C{bytes} @param key: The name of the cookie to get. @rtype: C{bytes} or C{None} @returns: The value of the specified cookie, or L{None} if that cookie was not present in the request. """ return self.received_cookies.get(key)
Get a cookie that was sent from the network. @type key: C{bytes} @param key: The name of the cookie to get. @rtype: C{bytes} or C{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/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def notifyFinish(self): """ Notify when the response to this request has finished. @note: There are some caveats around the reliability of the delivery of this notification. 1. If this L{Request}'s channel is paused, the notification will not be delivered. This can happen in one of two ways; either you can call C{request.transport.pauseProducing} yourself, or, 2. In order to deliver this notification promptly when a client disconnects, the reactor must continue reading from the transport, so that it can tell when the underlying network connection has gone away. Twisted Web will only keep reading up until a finite (small) maximum buffer size before it gives up and pauses the transport itself. If this occurs, you will not discover that the connection has gone away until a timeout fires or until the application attempts to send some data via L{Request.write}. 3. It is theoretically impossible to distinguish between successfully I{sending} a response and the peer successfully I{receiving} it. There are several networking edge cases where the L{Deferred}s returned by C{notifyFinish} will indicate success, but the data will never be received. There are also edge cases where the connection will appear to fail, but in reality the response was delivered. As a result, the information provided by the result of the L{Deferred}s returned by this method should be treated as a guess; do not make critical decisions in your applications based upon it. @rtype: L{Deferred} @return: A L{Deferred} which will be triggered when the request is finished -- with a L{None} value if the request finishes successfully or with an error if the request is interrupted by an error (for example, the client closing the connection prematurely). """ self.notifications.append(Deferred()) return self.notifications[-1]
Notify when the response to this request has finished. @note: There are some caveats around the reliability of the delivery of this notification. 1. If this L{Request}'s channel is paused, the notification will not be delivered. This can happen in one of two ways; either you can call C{request.transport.pauseProducing} yourself, or, 2. In order to deliver this notification promptly when a client disconnects, the reactor must continue reading from the transport, so that it can tell when the underlying network connection has gone away. Twisted Web will only keep reading up until a finite (small) maximum buffer size before it gives up and pauses the transport itself. If this occurs, you will not discover that the connection has gone away until a timeout fires or until the application attempts to send some data via L{Request.write}. 3. It is theoretically impossible to distinguish between successfully I{sending} a response and the peer successfully I{receiving} it. There are several networking edge cases where the L{Deferred}s returned by C{notifyFinish} will indicate success, but the data will never be received. There are also edge cases where the connection will appear to fail, but in reality the response was delivered. As a result, the information provided by the result of the L{Deferred}s returned by this method should be treated as a guess; do not make critical decisions in your applications based upon it. @rtype: L{Deferred} @return: A L{Deferred} which will be triggered when the request is finished -- with a L{None} value if the request finishes successfully or with an error if the request is interrupted by an error (for example, the client closing the connection prematurely).
notifyFinish
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def finish(self): """ Indicate that all response data has been written to this L{Request}. """ if self._disconnected: raise RuntimeError( "Request.finish called on a request after its connection was lost; " "use Request.notifyFinish to keep track of this.") if self.finished: warnings.warn("Warning! request.finish called twice.", stacklevel=2) return if not self.startedWriting: # write headers self.write(b'') if self.chunked: # write last chunk and closing CRLF self.channel.write(b"0\r\n\r\n") # log request if (hasattr(self.channel, "factory") and self.channel.factory is not None): self.channel.factory.log(self) self.finished = 1 if not self.queued: self._cleanup()
Indicate that all response data has been written to this L{Request}.
finish
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def write(self, data): """ Write some data as a result of an HTTP request. The first time this is called, it writes out response data. @type data: C{bytes} @param data: Some bytes to be sent as part of the response body. """ if self.finished: raise RuntimeError('Request.write called on a request after ' 'Request.finish was called.') if self._disconnected: # Don't attempt to write any data to a disconnected client. # The RuntimeError exception will be thrown as usual when # request.finish is called return if not self.startedWriting: self.startedWriting = 1 version = self.clientproto code = intToBytes(self.code) reason = self.code_message headers = [] # if we don't have a content length, we send data in # chunked mode, so that we can support pipelining in # persistent connections. if ((version == b"HTTP/1.1") and (self.responseHeaders.getRawHeaders(b'content-length') is None) and self.method != b"HEAD" and self.code not in NO_BODY_CODES): headers.append((b'Transfer-Encoding', b'chunked')) self.chunked = 1 if self.lastModified is not None: if self.responseHeaders.hasHeader(b'last-modified'): self._log.info( "Warning: last-modified specified both in" " header list and lastModified attribute." ) else: self.responseHeaders.setRawHeaders( b'last-modified', [datetimeToString(self.lastModified)]) if self.etag is not None: self.responseHeaders.setRawHeaders(b'ETag', [self.etag]) for name, values in self.responseHeaders.getAllRawHeaders(): for value in values: headers.append((name, value)) for cookie in self.cookies: headers.append((b'Set-Cookie', cookie)) self.channel.writeHeaders(version, code, reason, headers) # if this is a "HEAD" request, we shouldn't return any data if self.method == b"HEAD": self.write = lambda data: None return # for certain result codes, we should never return any data if self.code in NO_BODY_CODES: self.write = lambda data: None return self.sentLength = self.sentLength + len(data) if data: if self.chunked: self.channel.writeSequence(toChunk(data)) else: self.channel.write(data)
Write some data as a result of an HTTP request. The first time this is called, it writes out response data. @type data: C{bytes} @param data: Some bytes to be sent as part of the response body.
write
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def _ensureBytes(val): """ Ensure that C{val} is bytes, encoding using UTF-8 if needed. @param val: L{bytes} or L{unicode} @return: L{bytes} """ if val is None: # It's None, so we don't want to touch it return val if isinstance(val, bytes): return val else: return val.encode('utf8')
Ensure that C{val} is bytes, encoding using UTF-8 if needed. @param val: L{bytes} or L{unicode} @return: L{bytes}
addCookie._ensureBytes
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def _sanitize(val): """ Replace linear whitespace (C{\r}, C{\n}, C{\r\n}) and semicolons C{;} in C{val} with a single space. @param val: L{bytes} @return: L{bytes} """ return _sanitizeLinearWhitespace(val).replace(b';', b' ')
Replace linear whitespace (C{\r}, C{\n}, C{\r\n}) and semicolons C{;} in C{val} with a single space. @param val: L{bytes} @return: L{bytes}
addCookie._sanitize
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def addCookie(self, k, v, expires=None, domain=None, path=None, max_age=None, comment=None, secure=None, httpOnly=False, sameSite=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. @param k: cookie name @type k: L{bytes} or L{unicode} @param v: cookie value @type v: L{bytes} or L{unicode} @param expires: cookie expire attribute value in "Wdy, DD Mon YYYY HH:MM:SS GMT" format @type expires: L{bytes} or L{unicode} @param domain: cookie domain @type domain: L{bytes} or L{unicode} @param path: cookie path @type path: L{bytes} or L{unicode} @param max_age: cookie expiration in seconds from reception @type max_age: L{bytes} or L{unicode} @param comment: cookie comment @type comment: L{bytes} or L{unicode} @param secure: direct browser to send the cookie on encrypted connections only @type secure: L{bool} @param httpOnly: direct browser not to expose cookies through channels other than HTTP (and HTTPS) requests @type httpOnly: L{bool} @param sameSite: One of L{None} (default), C{'lax'} or C{'strict'}. Direct browsers not to send this cookie on cross-origin requests. Please see: U{https://tools.ietf.org/html/draft-west-first-party-cookies-07} @type sameSite: L{None}, L{bytes} or L{unicode} @raises: L{DeprecationWarning} if an argument is not L{bytes} or L{unicode}. L{ValueError} if the value for C{sameSite} is not supported. """ def _ensureBytes(val): """ Ensure that C{val} is bytes, encoding using UTF-8 if needed. @param val: L{bytes} or L{unicode} @return: L{bytes} """ if val is None: # It's None, so we don't want to touch it return val if isinstance(val, bytes): return val else: return val.encode('utf8') def _sanitize(val): """ Replace linear whitespace (C{\r}, C{\n}, C{\r\n}) and semicolons C{;} in C{val} with a single space. @param val: L{bytes} @return: L{bytes} """ return _sanitizeLinearWhitespace(val).replace(b';', b' ') cookie = ( _sanitize(_ensureBytes(k)) + b"=" + _sanitize(_ensureBytes(v))) if expires is not None: cookie = cookie + b"; Expires=" + _sanitize(_ensureBytes(expires)) if domain is not None: cookie = cookie + b"; Domain=" + _sanitize(_ensureBytes(domain)) if path is not None: cookie = cookie + b"; Path=" + _sanitize(_ensureBytes(path)) if max_age is not None: cookie = cookie + b"; Max-Age=" + _sanitize(_ensureBytes(max_age)) if comment is not None: cookie = cookie + b"; Comment=" + _sanitize(_ensureBytes(comment)) if secure: cookie = cookie + b"; Secure" if httpOnly: cookie = cookie + b"; HttpOnly" if sameSite: sameSite = _ensureBytes(sameSite).lower() if sameSite not in [b"lax", b"strict"]: raise ValueError( "Invalid value for sameSite: " + repr(sameSite)) cookie += b"; SameSite=" + sameSite self.cookies.append(cookie)
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. @param k: cookie name @type k: L{bytes} or L{unicode} @param v: cookie value @type v: L{bytes} or L{unicode} @param expires: cookie expire attribute value in "Wdy, DD Mon YYYY HH:MM:SS GMT" format @type expires: L{bytes} or L{unicode} @param domain: cookie domain @type domain: L{bytes} or L{unicode} @param path: cookie path @type path: L{bytes} or L{unicode} @param max_age: cookie expiration in seconds from reception @type max_age: L{bytes} or L{unicode} @param comment: cookie comment @type comment: L{bytes} or L{unicode} @param secure: direct browser to send the cookie on encrypted connections only @type secure: L{bool} @param httpOnly: direct browser not to expose cookies through channels other than HTTP (and HTTPS) requests @type httpOnly: L{bool} @param sameSite: One of L{None} (default), C{'lax'} or C{'strict'}. Direct browsers not to send this cookie on cross-origin requests. Please see: U{https://tools.ietf.org/html/draft-west-first-party-cookies-07} @type sameSite: L{None}, L{bytes} or L{unicode} @raises: L{DeprecationWarning} if an argument is not L{bytes} or L{unicode}. L{ValueError} if the value for C{sameSite} is not supported.
addCookie
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def setResponseCode(self, code, message=None): """ Set the HTTP response code. @type code: L{int} @type message: L{bytes} """ if not isinstance(code, _intTypes): raise TypeError("HTTP response code must be int or long") self.code = code if message: if not isinstance(message, bytes): raise TypeError("HTTP response status message must be bytes") self.code_message = message else: self.code_message = RESPONSES.get(code, b"Unknown Status")
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/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def setHeader(self, name, value): """ 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. """ self.responseHeaders.setRawHeaders(name, [value])
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/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def redirect(self, url): """ Utility function that does a redirect. Set the response code to L{FOUND} and the I{Location} header to the given URL. The request should have C{finish()} called after this. @param url: I{Location} header value. @type url: L{bytes} or L{str} """ self.setResponseCode(FOUND) self.setHeader(b"location", url)
Utility function that does a redirect. Set the response code to L{FOUND} and the I{Location} header to the given URL. The request should have C{finish()} called after this. @param url: I{Location} header value. @type url: L{bytes} or L{str}
redirect
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def setLastModified(self, 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} if appropriate for the time given. @param when: The last time the resource being returned was modified, in seconds since the epoch. @type when: number @return: If I am a I{If-Modified-Since} conditional request and the time given is not newer than the condition, I return L{http.CACHED<CACHED>} to indicate that you should write no body. Otherwise, I return a false value. """ # time.time() may be a float, but the HTTP-date strings are # only good for whole seconds. when = int(math.ceil(when)) if (not self.lastModified) or (self.lastModified < when): self.lastModified = when modifiedSince = self.getHeader(b'if-modified-since') if modifiedSince: firstPart = modifiedSince.split(b';', 1)[0] try: modifiedSince = stringToDatetime(firstPart) except ValueError: return None if modifiedSince >= self.lastModified: self.setResponseCode(NOT_MODIFIED) return CACHED return None
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} if appropriate for the time given. @param when: The last time the resource being returned was modified, in seconds since the epoch. @type when: number @return: If I am a I{If-Modified-Since} conditional request and the time given is not newer than the condition, I return L{http.CACHED<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/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def setETag(self, etag): """ Set an C{entity tag} for the outgoing response. That's \"entity tag\" as in the HTTP/1.1 C{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} or L{PRECONDITION_FAILED}, if appropriate for the tag given. @param etag: The entity tag for the resource being returned. @type etag: string @return: If I am a C{If-None-Match} conditional request and the tag matches one in the request, I return L{http.CACHED<CACHED>} to indicate that you should write no body. Otherwise, I return a false value. """ if etag: self.etag = etag tags = self.getHeader(b"if-none-match") if tags: tags = tags.split() if (etag in tags) or (b'*' in tags): self.setResponseCode(((self.method in (b"HEAD", b"GET")) and NOT_MODIFIED) or PRECONDITION_FAILED) return CACHED return None
Set an C{entity tag} for the outgoing response. That's \"entity tag\" as in the HTTP/1.1 C{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} or L{PRECONDITION_FAILED}, if appropriate for the tag given. @param etag: The entity tag for the resource being returned. @type etag: string @return: If I am a C{If-None-Match} conditional request and the tag matches one in the request, I return L{http.CACHED<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/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getAllHeaders(self): """ 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{self.requestHeaders.getAllRawHeaders()} may be preferred. """ headers = {} for k, v in self.requestHeaders.getAllRawHeaders(): headers[k.lower()] = v[-1] return headers
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{self.requestHeaders.getAllRawHeaders()} may be preferred.
getAllHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getRequestHostname(self): """ 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: C{bytes} """ # XXX This method probably has no unit tests. I changed it a ton and # nothing failed. host = self.getHeader(b'host') if host: return host.split(b':', 1)[0] return networkString(self.getHost().host)
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: C{bytes}
getRequestHostname
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getHost(self): """ Get my originally requesting transport's host. Don't rely on the 'transport' attribute, since Request objects may be copied remotely. For information on this method's return value, see L{twisted.internet.tcp.Port}. """ return self.host
Get my originally requesting transport's host. Don't rely on the 'transport' attribute, since Request objects may be copied remotely. For information on this method's return value, see L{twisted.internet.tcp.Port}.
getHost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def setHost(self, 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 b'http://localhost:8080/', they should say b'https://www.example.com/', so we do:: request.setHost(b'www.example.com', 443, ssl=1) @type host: C{bytes} @param host: The value to which to change the host header. @type ssl: C{bool} @param ssl: A flag which, if C{True}, indicates that the request is considered secure (if C{True}, L{isSecure} will return C{True}). """ self._forceSSL = ssl # set first so isSecure will work if self.isSecure(): default = 443 else: default = 80 if port == default: hostHeader = host else: hostHeader = host + b":" + intToBytes(port) self.requestHeaders.setRawHeaders(b"host", [hostHeader]) self.host = address.IPv4Address("TCP", host, port)
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 b'http://localhost:8080/', they should say b'https://www.example.com/', so we do:: request.setHost(b'www.example.com', 443, ssl=1) @type host: C{bytes} @param host: The value to which to change the host header. @type ssl: C{bool} @param ssl: A flag which, if C{True}, indicates that the request is considered secure (if C{True}, L{isSecure} will return C{True}).
setHost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getClientIP(self): """ Return the IP address of the client who submitted this request. This method is B{deprecated}. Use L{getClientAddress} instead. @returns: the client IP address @rtype: C{str} """ if isinstance(self.client, (address.IPv4Address, address.IPv6Address)): return self.client.host else: return None
Return the IP address of the client who submitted this request. This method is B{deprecated}. Use L{getClientAddress} instead. @returns: the client IP address @rtype: C{str}
getClientIP
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getClientAddress(self): """ Return the address of the client who submitted this request. This may not be a network address (e.g., a server listening on a UNIX domain socket will cause this to return L{UNIXAddress}). Callers must check the type of the returned address. @since: 18.4 @return: the client's address. @rtype: L{IAddress} """ return self.client
Return the address of the client who submitted this request. This may not be a network address (e.g., a server listening on a UNIX domain socket will cause this to return L{UNIXAddress}). Callers must check the type of the returned address. @since: 18.4 @return: the client's address. @rtype: L{IAddress}
getClientAddress
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def isSecure(self): """ Return L{True} if this request is using a secure transport. Normally this method returns L{True} if this request's L{HTTPChannel} instance is using a transport that implements L{interfaces.ISSLTransport}. This will also return L{True} if L{Request.setHost} has been called with C{ssl=True}. @returns: L{True} if this request is secure @rtype: C{bool} """ if self._forceSSL: return True channel = getattr(self, 'channel', None) if channel is None: return False return channel.isSecure()
Return L{True} if this request is using a secure transport. Normally this method returns L{True} if this request's L{HTTPChannel} instance is using a transport that implements L{interfaces.ISSLTransport}. This will also return L{True} if L{Request.setHost} has been called with C{ssl=True}. @returns: L{True} if this request is secure @rtype: C{bool}
isSecure
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getUser(self): """ 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: C{bytes} """ try: return self.user except: pass self._authorize() return self.user
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: C{bytes}
getUser
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getPassword(self): """ 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: C{bytes} """ try: return self.password except: pass self._authorize() return self.password
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: C{bytes}
getPassword
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def connectionLost(self, reason): """ There is no longer a connection for this request to respond over. Clean up anything which can't be useful anymore. """ self._disconnected = True self.channel = None if self.content is not None: self.content.close() for d in self.notifications: d.errback(reason) self.notifications = []
There is no longer a connection for this request to respond over. Clean up anything which can't be useful anymore.
connectionLost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT