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
182
url
stringlengths
46
251
license
stringclasses
4 values
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 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 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 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
def loseConnection(self): """ Pass the loseConnection through to the underlying channel. """ if self.channel is not None: self.channel.loseConnection()
Pass the loseConnection through to the underlying channel.
loseConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def __hash__(self): """ A C{Request} is hashable so that it can be used as a mapping key. @return: A C{int} based on the instance's identity. """ return id(self)
A C{Request} is hashable so that it can be used as a mapping key. @return: A C{int} based on the instance's identity.
__hash__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def dataReceived(self, data): """ Interpret the next chunk of bytes received. Either deliver them to the data callback or invoke the finish callback if enough bytes have been received. @raise RuntimeError: If the finish callback has already been invoked during a previous call to this methood. """ if self.dataCallback is None: raise RuntimeError( "_IdentityTransferDecoder cannot decode data after finishing") if self.contentLength is None: self.dataCallback(data) elif len(data) < self.contentLength: self.contentLength -= len(data) self.dataCallback(data) else: # Make the state consistent before invoking any code belonging to # anyone else in case noMoreData ends up being called beneath this # stack frame. contentLength = self.contentLength dataCallback = self.dataCallback finishCallback = self.finishCallback self.dataCallback = self.finishCallback = None self.contentLength = 0 dataCallback(data[:contentLength]) finishCallback(data[contentLength:])
Interpret the next chunk of bytes received. Either deliver them to the data callback or invoke the finish callback if enough bytes have been received. @raise RuntimeError: If the finish callback has already been invoked during a previous call to this methood.
dataReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def noMoreData(self): """ All data which will be delivered to this decoder has been. Check to make sure as much data as was expected has been received. @raise PotentialDataLoss: If the content length is unknown. @raise _DataLoss: If the content length is known and fewer than that many bytes have been delivered. @return: L{None} """ finishCallback = self.finishCallback self.dataCallback = self.finishCallback = None if self.contentLength is None: finishCallback(b'') raise PotentialDataLoss() elif self.contentLength != 0: raise _DataLoss()
All data which will be delivered to this decoder has been. Check to make sure as much data as was expected has been received. @raise PotentialDataLoss: If the content length is unknown. @raise _DataLoss: If the content length is known and fewer than that many bytes have been delivered. @return: L{None}
noMoreData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def dataReceived(self, data): """ Interpret data from a request or response body which uses the I{chunked} Transfer-Encoding. """ data = self._buffer + data self._buffer = b'' while data: data = getattr(self, '_dataReceived_%s' % (self.state,))(data)
Interpret data from a request or response body which uses the I{chunked} Transfer-Encoding.
dataReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def noMoreData(self): """ Verify that all data has been received. If it has not been, raise L{_DataLoss}. """ if self.state != 'FINISHED': raise _DataLoss( "Chunked decoder in %r state, still expecting more data to " "get to 'FINISHED' state." % (self.state,))
Verify that all data has been received. If it has not been, raise L{_DataLoss}.
noMoreData
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def pauseProducing(self): """ Pause producing data. Tells a producer that it has produced too much data to process for the time being, and to stop until resumeProducing() is called. """ pass
Pause producing data. Tells a producer that it has produced too much data to process for the time being, and to stop until resumeProducing() is called.
pauseProducing
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def registerProducer(self, producer, streaming): """ Register to receive data from a producer. @param producer: The producer to register. @param streaming: Whether this is a streaming producer or not. """ pass
Register to receive data from a producer. @param producer: The producer to register. @param streaming: Whether this is a streaming producer or not.
registerProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def lineReceived(self, line): """ Called for each line from request until the end of headers when it enters binary mode. """ self.resetTimeout() self._receivedHeaderSize += len(line) if (self._receivedHeaderSize > self.totalHeadersSize): self._respondToBadRequestAndDisconnect() return if self.__first_line: # if this connection is not persistent, drop any data which # the client (illegally) sent after the last request. if not self.persistent: self.dataReceived = self.lineReceived = lambda *args: None return # IE sends an extraneous empty line (\r\n) after a POST request; # eat up such a line, but only ONCE if not line and self.__first_line == 1: self.__first_line = 2 return # create a new Request object if INonQueuedRequestFactory.providedBy(self.requestFactory): request = self.requestFactory(self) else: request = self.requestFactory(self, len(self.requests)) self.requests.append(request) self.__first_line = 0 parts = line.split() if len(parts) != 3: self._respondToBadRequestAndDisconnect() return command, request, version = parts try: command.decode("ascii") except UnicodeDecodeError: self._respondToBadRequestAndDisconnect() return self._command = command self._path = request self._version = version elif line == b'': # End of headers. if self.__header: ok = self.headerReceived(self.__header) # If the last header we got is invalid, we MUST NOT proceed # with processing. We'll have sent a 400 anyway, so just stop. if not ok: return self.__header = b'' self.allHeadersReceived() if self.length == 0: self.allContentReceived() else: self.setRawMode() elif line[0] in b' \t': # Continuation of a multi line header. self.__header = self.__header + b'\n' + line # Regular header line. # Processing of header line is delayed to allow accumulating multi # line headers. else: if self.__header: self.headerReceived(self.__header) self.__header = line
Called for each line from request until the end of headers when it enters binary mode.
lineReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def headerReceived(self, line): """ Do pre-processing (for content-length) and store this header away. Enforce the per-request header limit. @type line: C{bytes} @param line: A line from the header section of a request, excluding the line delimiter. @return: A flag indicating whether the header was valid. @rtype: L{bool} """ try: header, data = line.split(b':', 1) except ValueError: self._respondToBadRequestAndDisconnect() return False header = header.lower() data = data.strip() if header == b'content-length': try: self.length = int(data) except ValueError: self._respondToBadRequestAndDisconnect() self.length = None return False self._transferDecoder = _IdentityTransferDecoder( self.length, self.requests[-1].handleContentChunk, self._finishRequestBody) elif header == b'transfer-encoding' and data.lower() == b'chunked': # XXX Rather poorly tested code block, apparently only exercised by # test_chunkedEncoding self.length = None self._transferDecoder = _ChunkedTransferDecoder( self.requests[-1].handleContentChunk, self._finishRequestBody) reqHeaders = self.requests[-1].requestHeaders values = reqHeaders.getRawHeaders(header) if values is not None: values.append(data) else: reqHeaders.setRawHeaders(header, [data]) self._receivedHeaderCount += 1 if self._receivedHeaderCount > self.maxHeaders: self._respondToBadRequestAndDisconnect() return False return True
Do pre-processing (for content-length) and store this header away. Enforce the per-request header limit. @type line: C{bytes} @param line: A line from the header section of a request, excluding the line delimiter. @return: A flag indicating whether the header was valid. @rtype: L{bool}
headerReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def dataReceived(self, data): """ Data was received from the network. Process it. """ # If we're currently handling a request, buffer this data. if self._handlingRequest: self._dataBuffer.append(data) if ( (sum(map(len, self._dataBuffer)) > self._optimisticEagerReadSize) and not self._waitingForTransport ): # If we received more data than a small limit while processing # the head-of-line request, apply TCP backpressure to our peer # to get them to stop sending more request data until we're # ready. See docstring for _optimisticEagerReadSize above. self._networkProducer.pauseProducing() return return basic.LineReceiver.dataReceived(self, data)
Data was received from the network. Process it.
dataReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def checkPersistence(self, request, version): """ Check if the channel should close or not. @param request: The request most recently received over this channel against which checks will be made to determine if this connection can remain open after a matching response is returned. @type version: C{bytes} @param version: The version of the request. @rtype: C{bool} @return: A flag which, if C{True}, indicates that this connection may remain open to receive another request; if C{False}, the connection must be closed in order to indicate the completion of the response to C{request}. """ connection = request.requestHeaders.getRawHeaders(b'connection') if connection: tokens = [t.lower() for t in connection[0].split(b' ')] else: tokens = [] # Once any HTTP 0.9 or HTTP 1.0 request is received, the connection is # no longer allowed to be persistent. At this point in processing the # request, we don't yet know if it will be possible to set a # Content-Length in the response. If it is not, then the connection # will have to be closed to end an HTTP 0.9 or HTTP 1.0 response. # If the checkPersistence call happened later, after the Content-Length # has been determined (or determined not to be set), it would probably # be possible to have persistent connections with HTTP 0.9 and HTTP 1.0. # This may not be worth the effort, though. Just use HTTP 1.1, okay? if version == b"HTTP/1.1": if b'close' in tokens: request.responseHeaders.setRawHeaders(b'connection', [b'close']) return False else: return True else: return False
Check if the channel should close or not. @param request: The request most recently received over this channel against which checks will be made to determine if this connection can remain open after a matching response is returned. @type version: C{bytes} @param version: The version of the request. @rtype: C{bool} @return: A flag which, if C{True}, indicates that this connection may remain open to receive another request; if C{False}, the connection must be closed in order to indicate the completion of the response to C{request}.
checkPersistence
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def isSecure(self): """ Return L{True} if this channel is using a secure transport. Normally this method returns L{True} if this instance is using a transport that implements L{interfaces.ISSLTransport}. @returns: L{True} if this request is secure @rtype: C{bool} """ if interfaces.ISSLTransport(self.transport, None) is not None: return True return False
Return L{True} if this channel is using a secure transport. Normally this method returns L{True} if this instance is using a transport that implements L{interfaces.ISSLTransport}. @returns: L{True} if this request is secure @rtype: C{bool}
isSecure
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def writeHeaders(self, version, code, reason, headers): """ Called by L{Request} objects to write a complete set of HTTP headers to a transport. @param version: The HTTP version in use. @type version: L{bytes} @param code: The HTTP status code to write. @type code: L{bytes} @param reason: The HTTP reason phrase to write. @type reason: L{bytes} @param headers: The headers to write to the transport. @type headers: L{twisted.web.http_headers.Headers} """ sanitizedHeaders = Headers() for name, value in headers: sanitizedHeaders.addRawHeader(name, value) responseLine = version + b" " + code + b" " + reason + b"\r\n" headerSequence = [responseLine] headerSequence.extend( name + b': ' + value + b"\r\n" for name, values in sanitizedHeaders.getAllRawHeaders() for value in values ) headerSequence.append(b"\r\n") self.transport.writeSequence(headerSequence)
Called by L{Request} objects to write a complete set of HTTP headers to a transport. @param version: The HTTP version in use. @type version: L{bytes} @param code: The HTTP status code to write. @type code: L{bytes} @param reason: The HTTP reason phrase to write. @type reason: L{bytes} @param headers: The headers to write to the transport. @type headers: L{twisted.web.http_headers.Headers}
writeHeaders
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def write(self, data): """ Called by L{Request} objects to write response data. @param data: The data chunk to write to the stream. @type data: L{bytes} @return: L{None} """ self.transport.write(data)
Called by L{Request} objects to write response data. @param data: The data chunk to write to the stream. @type data: L{bytes} @return: L{None}
write
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def writeSequence(self, iovec): """ Write a list of strings to the HTTP response. @param iovec: A list of byte strings to write to the stream. @type data: L{list} of L{bytes} @return: L{None} """ self.transport.writeSequence(iovec)
Write a list of strings to the HTTP response. @param iovec: A list of byte strings to write to the stream. @type data: L{list} of L{bytes} @return: L{None}
writeSequence
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getPeer(self): """ Get the remote address of this connection. @return: An L{IAddress} provider. """ return self.transport.getPeer()
Get the remote address of this connection. @return: An L{IAddress} provider.
getPeer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getHost(self): """ Get the local address of this connection. @return: An L{IAddress} provider. """ return self.transport.getHost()
Get the local address of this connection. @return: An L{IAddress} provider.
getHost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def loseConnection(self): """ Closes the connection. Will write any data that is pending to be sent on the network, but if this response has not yet been written to the network will not write anything. @return: L{None} """ self._networkProducer.unregisterProducer() return self.transport.loseConnection()
Closes the connection. Will write any data that is pending to be sent on the network, but if this response has not yet been written to the network will not write anything. @return: L{None}
loseConnection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def registerProducer(self, producer, streaming): """ Register to receive data from a producer. This sets self to be a consumer for a producer. When this object runs out of data (as when a send(2) call on a socket succeeds in moving the last data from a userspace buffer into a kernelspace buffer), it will ask the producer to resumeProducing(). For L{IPullProducer} providers, C{resumeProducing} will be called once each time data is required. For L{IPushProducer} providers, C{pauseProducing} will be called whenever the write buffer fills up and C{resumeProducing} will only be called when it empties. @type producer: L{IProducer} provider @param producer: The L{IProducer} that will be producing data. @type streaming: L{bool} @param streaming: C{True} if C{producer} provides L{IPushProducer}, C{False} if C{producer} provides L{IPullProducer}. @raise RuntimeError: If a producer is already registered. @return: L{None} """ if self._requestProducer is not None: raise RuntimeError( "Cannot register producer %s, because producer %s was never " "unregistered." % (producer, self._requestProducer)) if not streaming: producer = _PullToPush(producer, self) self._requestProducer = producer self._requestProducerStreaming = streaming if not streaming: producer.startStreaming()
Register to receive data from a producer. This sets self to be a consumer for a producer. When this object runs out of data (as when a send(2) call on a socket succeeds in moving the last data from a userspace buffer into a kernelspace buffer), it will ask the producer to resumeProducing(). For L{IPullProducer} providers, C{resumeProducing} will be called once each time data is required. For L{IPushProducer} providers, C{pauseProducing} will be called whenever the write buffer fills up and C{resumeProducing} will only be called when it empties. @type producer: L{IProducer} provider @param producer: The L{IProducer} that will be producing data. @type streaming: L{bool} @param streaming: C{True} if C{producer} provides L{IPushProducer}, C{False} if C{producer} provides L{IPullProducer}. @raise RuntimeError: If a producer is already registered. @return: L{None}
registerProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def unregisterProducer(self): """ Stop consuming data from a producer, without disconnecting. @return: L{None} """ if self._requestProducer is None: return if not self._requestProducerStreaming: self._requestProducer.stopStreaming() self._requestProducer = None self._requestProducerStreaming = None
Stop consuming data from a producer, without disconnecting. @return: L{None}
unregisterProducer
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def stopProducing(self): """ Stop producing data. The HTTPChannel doesn't *actually* implement this, beacuse the assumption is that it will only be called just before C{loseConnection} is called. There's nothing sensible we can do other than call C{loseConnection} anyway. """ if self._requestProducer is not None: self._requestProducer.stopProducing()
Stop producing data. The HTTPChannel doesn't *actually* implement this, beacuse the assumption is that it will only be called just before C{loseConnection} is called. There's nothing sensible we can do other than call C{loseConnection} anyway.
stopProducing
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def pauseProducing(self): """ Pause producing data. This will be called by the transport when the send buffers have been filled up. We want to simultaneously pause the producing L{Request} object and also pause our transport. The logic behind pausing the transport is specifically to avoid issues like https://twistedmatrix.com/trac/ticket/8868. In this case, our inability to send does not prevent us handling more requests, which means we increasingly queue up more responses in our send buffer without end. The easiest way to handle this is to ensure that if we are unable to send our responses, we will not read further data from the connection until the client pulls some data out. This is a bit of a blunt instrument, but it's ok. Note that this potentially interacts with timeout handling in a positive way. Once the transport is paused the client may run into a timeout which will cause us to tear the connection down. That's a good thing! """ self._waitingForTransport = True # The first step is to tell any producer we might currently have # registered to stop producing. If we can slow our applications down # we should. if self._requestProducer is not None: self._requestProducer.pauseProducing() # The next step here is to pause our own transport, as discussed in the # docstring. if not self._handlingRequest: self._networkProducer.pauseProducing()
Pause producing data. This will be called by the transport when the send buffers have been filled up. We want to simultaneously pause the producing L{Request} object and also pause our transport. The logic behind pausing the transport is specifically to avoid issues like https://twistedmatrix.com/trac/ticket/8868. In this case, our inability to send does not prevent us handling more requests, which means we increasingly queue up more responses in our send buffer without end. The easiest way to handle this is to ensure that if we are unable to send our responses, we will not read further data from the connection until the client pulls some data out. This is a bit of a blunt instrument, but it's ok. Note that this potentially interacts with timeout handling in a positive way. Once the transport is paused the client may run into a timeout which will cause us to tear the connection down. That's a good thing!
pauseProducing
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def resumeProducing(self): """ Resume producing data. This will be called by the transport when the send buffer has dropped enough to actually send more data. When this happens we can unpause any outstanding L{Request} producers we have, and also unpause our transport. """ self._waitingForTransport = False if self._requestProducer is not None: self._requestProducer.resumeProducing() # We only want to resume the network producer if we're not currently # waiting for a response to show up. if not self._handlingRequest: self._networkProducer.resumeProducing()
Resume producing data. This will be called by the transport when the send buffer has dropped enough to actually send more data. When this happens we can unpause any outstanding L{Request} producers we have, and also unpause our transport.
resumeProducing
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def _respondToBadRequestAndDisconnect(self): """ This is a quick and dirty way of responding to bad requests. As described by HTTP standard we should be patient and accept the whole request from the client before sending a polite bad request response, even in the case when clients send tons of data. @param transport: Transport handling connection to the client. @type transport: L{interfaces.ITransport} """ self.transport.write(b"HTTP/1.1 400 Bad Request\r\n\r\n") self.loseConnection()
This is a quick and dirty way of responding to bad requests. As described by HTTP standard we should be patient and accept the whole request from the client before sending a polite bad request response, even in the case when clients send tons of data. @param transport: Transport handling connection to the client. @type transport: L{interfaces.ITransport}
_respondToBadRequestAndDisconnect
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def _escape(s): """ Return a string like python repr, but always escaped as if surrounding quotes were double quotes. @param s: The string to escape. @type s: L{bytes} or L{unicode} @return: An escaped string. @rtype: L{unicode} """ if not isinstance(s, bytes): s = s.encode("ascii") r = repr(s) if not isinstance(r, unicode): r = r.decode("ascii") if r.startswith(u"b"): r = r[1:] if r.startswith(u"'"): return r[1:-1].replace(u'"', u'\\"').replace(u"\\'", u"'") return r[1:-1]
Return a string like python repr, but always escaped as if surrounding quotes were double quotes. @param s: The string to escape. @type s: L{bytes} or L{unicode} @return: An escaped string. @rtype: L{unicode}
_escape
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def combinedLogFormatter(timestamp, request): """ @return: A combined log formatted log line for the given request. @see: L{IAccessLogFormatter} """ clientAddr = request.getClientAddress() if isinstance(clientAddr, (address.IPv4Address, address.IPv6Address, _XForwardedForAddress)): ip = clientAddr.host else: ip = b'-' referrer = _escape(request.getHeader(b"referer") or b"-") agent = _escape(request.getHeader(b"user-agent") or b"-") line = ( u'"%(ip)s" - - %(timestamp)s "%(method)s %(uri)s %(protocol)s" ' u'%(code)d %(length)s "%(referrer)s" "%(agent)s"' % dict( ip=_escape(ip), timestamp=timestamp, method=_escape(request.method), uri=_escape(request.uri), protocol=_escape(request.clientproto), code=request.code, length=request.sentLength or u"-", referrer=referrer, agent=agent, )) return line
@return: A combined log formatted log line for the given request. @see: L{IAccessLogFormatter}
combinedLogFormatter
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def getClientAddress(self): """ The client address (the first address) in the value of the I{X-Forwarded-For header}. If the header is not present, the IP is considered to be C{b"-"}. @return: L{_XForwardedForAddress} which wraps the client address as expected by L{combinedLogFormatter}. """ host = self._request.requestHeaders.getRawHeaders( b"x-forwarded-for", [b"-"])[0].split(b",")[0].strip() return _XForwardedForAddress(host)
The client address (the first address) in the value of the I{X-Forwarded-For header}. If the header is not present, the IP is considered to be C{b"-"}. @return: L{_XForwardedForAddress} which wraps the client address as expected by L{combinedLogFormatter}.
getClientAddress
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def clientproto(self): """ @return: The protocol version in the request. @rtype: L{bytes} """ return self._request.clientproto
@return: The protocol version in the request. @rtype: L{bytes}
clientproto
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT