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 code(self): """ @return: The response code for the request. @rtype: L{int} """ return self._request.code
@return: The response code for the request. @rtype: L{int}
code
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def sentLength(self): """ @return: The number of bytes sent in the response body. @rtype: L{int} """ return self._request.sentLength
@return: The number of bytes sent in the response body. @rtype: L{int}
sentLength
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def proxiedLogFormatter(timestamp, request): """ @return: A combined log formatted log line for the given request but use the value of the I{X-Forwarded-For} header as the value for the client IP address. @see: L{IAccessLogFormatter} """ return combinedLogFormatter(timestamp, _XForwardedForRequest(request))
@return: A combined log formatted log line for the given request but use the value of the I{X-Forwarded-For} header as the value for the client IP address. @see: L{IAccessLogFormatter}
proxiedLogFormatter
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def factory(self): """ @see: L{_genericHTTPChannelProtocolFactory} """ return self._channel.factory
@see: L{_genericHTTPChannelProtocolFactory}
factory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def requestFactory(self): """ A callable to use to build L{IRequest} objects. Retries the object from the current backing channel. """ return self._channel.requestFactory
A callable to use to build L{IRequest} objects. Retries the object from the current backing channel.
requestFactory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def requestFactory(self, value): """ A callable to use to build L{IRequest} objects. Sets the object on the backing channel and also stores the value for propagation to any new channel. @param value: The new callable to use. @type value: A L{callable} returning L{IRequest} """ self._requestFactory = value self._channel.requestFactory = value
A callable to use to build L{IRequest} objects. Sets the object on the backing channel and also stores the value for propagation to any new channel. @param value: The new callable to use. @type value: A L{callable} returning L{IRequest}
requestFactory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def site(self): """ A reference to the creating L{twisted.web.server.Site} object. Returns the site object from the backing channel. """ return self._channel.site
A reference to the creating L{twisted.web.server.Site} object. Returns the site object from the backing channel.
site
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def site(self, value): """ A reference to the creating L{twisted.web.server.Site} object. Sets the object on the backing channel and also stores the value for propagation to any new channel. @param value: The L{twisted.web.server.Site} object to set. @type value: L{twisted.web.server.Site} """ self._site = value self._channel.site = value
A reference to the creating L{twisted.web.server.Site} object. Sets the object on the backing channel and also stores the value for propagation to any new channel. @param value: The L{twisted.web.server.Site} object to set. @type value: L{twisted.web.server.Site}
site
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def timeOut(self): """ The idle timeout for the backing channel. """ return self._channel.timeOut
The idle timeout for the backing channel.
timeOut
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def timeOut(self, value): """ The idle timeout for the backing channel. Sets the idle timeout on both the backing channel and stores it for propagation to any new backing channel. @param value: The timeout to set. @type value: L{int} or L{float} """ self._timeOut = value self._channel.timeOut = value
The idle timeout for the backing channel. Sets the idle timeout on both the backing channel and stores it for propagation to any new backing channel. @param value: The timeout to set. @type value: L{int} or L{float}
timeOut
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def callLater(self): """ A value for the C{callLater} callback. This callback is used by the L{twisted.protocols.policies.TimeoutMixin} to handle timeouts. """ return self._channel.callLater
A value for the C{callLater} callback. This callback is used by the L{twisted.protocols.policies.TimeoutMixin} to handle timeouts.
callLater
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def callLater(self, value): """ Sets the value for the C{callLater} callback. This callback is used by the L{twisted.protocols.policies.TimeoutMixin} to handle timeouts. @param value: The new callback to use. @type value: L{callable} """ self._callLater = value self._channel.callLater = value
Sets the value for the C{callLater} callback. This callback is used by the L{twisted.protocols.policies.TimeoutMixin} to handle timeouts. @param value: The new callback to use. @type value: L{callable}
callLater
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def dataReceived(self, data): """ An override of L{IProtocol.dataReceived} that checks what protocol we're using. """ if self._negotiatedProtocol is None: try: negotiatedProtocol = self._channel.transport.negotiatedProtocol except AttributeError: # Plaintext HTTP, always HTTP/1.1 negotiatedProtocol = b'http/1.1' if negotiatedProtocol is None: negotiatedProtocol = b'http/1.1' if negotiatedProtocol == b'h2': if not H2_ENABLED: raise ValueError("Negotiated HTTP/2 without support.") # We need to make sure that the HTTPChannel is unregistered # from the transport so that the H2Connection can register # itself if possible. self._channel._networkProducer.unregisterProducer() transport = self._channel.transport self._channel = H2Connection() self._channel.requestFactory = self._requestFactory self._channel.site = self._site self._channel.factory = self._factory self._channel.timeOut = self._timeOut self._channel.callLater = self._callLater self._channel.makeConnection(transport) else: # Only HTTP/2 and HTTP/1.1 are supported right now. assert negotiatedProtocol == b'http/1.1', \ "Unsupported protocol negotiated" self._negotiatedProtocol = negotiatedProtocol return self._channel.dataReceived(data)
An override of L{IProtocol.dataReceived} that checks what protocol we're using.
dataReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def _genericHTTPChannelProtocolFactory(self): """ Returns an appropriately initialized _GenericHTTPChannelProtocol. """ return _GenericHTTPChannelProtocol(HTTPChannel())
Returns an appropriately initialized _GenericHTTPChannelProtocol.
_genericHTTPChannelProtocolFactory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def __init__(self, logPath=None, timeout=_REQUEST_TIMEOUT, logFormatter=None, reactor=None): """ @param logPath: File path to which access log messages will be written or C{None} to disable logging. @type logPath: L{str} or L{bytes} @param timeout: The initial value of L{timeOut}, which defines the idle connection timeout in seconds, or C{None} to disable the idle timeout. @type timeout: L{float} @param logFormatter: An object to format requests into log lines for the access log. L{combinedLogFormatter} when C{None} is passed. @type logFormatter: L{IAccessLogFormatter} provider @param reactor: A L{IReactorTime} provider used to manage connection timeouts and compute logging timestamps. """ if not reactor: from twisted.internet import reactor self._reactor = reactor if logPath is not None: logPath = os.path.abspath(logPath) self.logPath = logPath self.timeOut = timeout if logFormatter is None: logFormatter = combinedLogFormatter self._logFormatter = logFormatter # For storing the cached log datetime and the callback to update it self._logDateTime = None self._logDateTimeCall = None
@param logPath: File path to which access log messages will be written or C{None} to disable logging. @type logPath: L{str} or L{bytes} @param timeout: The initial value of L{timeOut}, which defines the idle connection timeout in seconds, or C{None} to disable the idle timeout. @type timeout: L{float} @param logFormatter: An object to format requests into log lines for the access log. L{combinedLogFormatter} when C{None} is passed. @type logFormatter: L{IAccessLogFormatter} provider @param reactor: A L{IReactorTime} provider used to manage connection timeouts and compute logging timestamps.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def _updateLogDateTime(self): """ Update log datetime periodically, so we aren't always recalculating it. """ self._logDateTime = datetimeToLogString(self._reactor.seconds()) self._logDateTimeCall = self._reactor.callLater(1, self._updateLogDateTime)
Update log datetime periodically, so we aren't always recalculating it.
_updateLogDateTime
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def startFactory(self): """ Set up request logging if necessary. """ if self._logDateTimeCall is None: self._updateLogDateTime() if self.logPath: self.logFile = self._openLogFile(self.logPath) else: self.logFile = log.logfile
Set up request logging if necessary.
startFactory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def _openLogFile(self, path): """ Override in subclasses, e.g. to use L{twisted.python.logfile}. """ f = open(path, "ab", 1) return f
Override in subclasses, e.g. to use L{twisted.python.logfile}.
_openLogFile
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def log(self, request): """ Write a line representing C{request} to the access log file. @param request: The request object about which to log. @type request: L{Request} """ try: logFile = self.logFile except AttributeError: pass else: line = self._logFormatter(self._logDateTime, request) + u"\n" logFile.write(line.encode('utf8'))
Write a line representing C{request} to the access log file. @param request: The request object about which to log. @type request: L{Request}
log
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/http.py
MIT
def handleResponseEnd(self): """ Finish the original request, indicating that the response has been completely written to it, and disconnect the outgoing transport. """ if not self._finished: self._finished = True self.father.finish() self.transport.loseConnection()
Finish the original request, indicating that the response has been completely written to it, and disconnect the outgoing transport.
handleResponseEnd
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
MIT
def clientConnectionFailed(self, connector, reason): """ Report a connection failure in a response to the incoming request as an error. """ self.father.setResponseCode(501, b"Gateway error") self.father.responseHeaders.addRawHeader(b"Content-Type", b"text/html") self.father.write(b"<H1>Could not connect</H1>") self.father.finish()
Report a connection failure in a response to the incoming request as an error.
clientConnectionFailed
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
MIT
def process(self): """ Handle this request by connecting to the proxied server and forwarding it there, then forwarding the response back as the response to this request. """ self.requestHeaders.setRawHeaders(b"host", [self.factory.host.encode('ascii')]) clientFactory = self.proxyClientFactoryClass( self.method, self.uri, self.clientproto, self.getAllHeaders(), self.content.read(), self) self.reactor.connectTCP(self.factory.host, self.factory.port, clientFactory)
Handle this request by connecting to the proxied server and forwarding it there, then forwarding the response back as the response to this request.
process
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
MIT
def __init__(self, host, port, path, reactor=reactor): """ @param host: the host of the web server to proxy. @type host: C{str} @param port: the port of the web server to proxy. @type port: C{port} @param path: the base path to fetch data from. Note that you shouldn't put any trailing slashes in it, it will be added automatically in request. For example, if you put B{/foo}, a request on B{/bar} will be proxied to B{/foo/bar}. Any required encoding of special characters (such as " " or "/") should have been done already. @type path: C{bytes} """ Resource.__init__(self) self.host = host self.port = port self.path = path self.reactor = reactor
@param host: the host of the web server to proxy. @type host: C{str} @param port: the port of the web server to proxy. @type port: C{port} @param path: the base path to fetch data from. Note that you shouldn't put any trailing slashes in it, it will be added automatically in request. For example, if you put B{/foo}, a request on B{/bar} will be proxied to B{/foo/bar}. Any required encoding of special characters (such as " " or "/") should have been done already. @type path: C{bytes}
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
MIT
def getChild(self, path, request): """ Create and return a proxy resource with the same proxy configuration as this one, except that its path also contains the segment given by C{path} at the end. """ return ReverseProxyResource( self.host, self.port, self.path + b'/' + urlquote(path, safe=b"").encode('utf-8'), self.reactor)
Create and return a proxy resource with the same proxy configuration as this one, except that its path also contains the segment given by C{path} at the end.
getChild
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
MIT
def render(self, request): """ Render a request by forwarding it to the proxied server. """ # RFC 2616 tells us that we can omit the port if it's the default port, # but we have to provide it otherwise if self.port == 80: host = self.host else: host = u"%s:%d" % (self.host, self.port) request.requestHeaders.setRawHeaders(b"host", [host.encode('ascii')]) request.content.seek(0, 0) qs = urllib_parse.urlparse(request.uri)[4] if qs: rest = self.path + b'?' + qs else: rest = self.path clientFactory = self.proxyClientFactoryClass( request.method, rest, request.clientproto, request.getAllHeaders(), request.content.read(), request) self.reactor.connectTCP(self.host, self.port, clientFactory) return NOT_DONE_YET
Render a request by forwarding it to the proxied server.
render
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/proxy.py
MIT
def __init__(self, filename, registry=None, reactor=None): """ Initialize, with the name of a CGI script file. """ self.filename = filename if reactor is None: # This installs a default reactor, if None was installed before. # We do a late import here, so that importing the current module # won't directly trigger installing a default reactor. from twisted.internet import reactor self._reactor = reactor
Initialize, with the name of a CGI script file.
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py
MIT
def render(self, request): """ Do various things to conform to the CGI specification. I will set up the usual slew of environment variables, then spin off a process. @type request: L{twisted.web.http.Request} @param request: An HTTP request. """ scriptName = b"/" + b"/".join(request.prepath) serverName = request.getRequestHostname().split(b':')[0] env = {"SERVER_SOFTWARE": server.version, "SERVER_NAME": serverName, "GATEWAY_INTERFACE": "CGI/1.1", "SERVER_PROTOCOL": request.clientproto, "SERVER_PORT": str(request.getHost().port), "REQUEST_METHOD": request.method, "SCRIPT_NAME": scriptName, "SCRIPT_FILENAME": self.filename, "REQUEST_URI": request.uri} ip = request.getClientAddress().host if ip is not None: env['REMOTE_ADDR'] = ip pp = request.postpath if pp: env["PATH_INFO"] = "/" + "/".join(pp) if hasattr(request, "content"): # 'request.content' is either a StringIO or a TemporaryFile, and # the file pointer is sitting at the beginning (seek(0,0)) request.content.seek(0, 2) length = request.content.tell() request.content.seek(0, 0) env['CONTENT_LENGTH'] = str(length) try: qindex = request.uri.index(b'?') except ValueError: env['QUERY_STRING'] = '' qargs = [] else: qs = env['QUERY_STRING'] = request.uri[qindex+1:] if '=' in qs: qargs = [] else: qargs = [urllib.unquote(x) for x in qs.split('+')] # Propagate HTTP headers for title, header in request.getAllHeaders().items(): envname = title.replace(b'-', b'_').upper() if title not in (b'content-type', b'content-length', b'proxy'): envname = b"HTTP_" + envname env[envname] = header # Propagate our environment for key, value in os.environ.items(): if key not in env: env[key] = value # And they're off! self.runProcess(env, request, qargs) return server.NOT_DONE_YET
Do various things to conform to the CGI specification. I will set up the usual slew of environment variables, then spin off a process. @type request: L{twisted.web.http.Request} @param request: An HTTP request.
render
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py
MIT
def runProcess(self, env, request, qargs=[]): """ Run the cgi script. @type env: A L{dict} of L{str}, or L{None} @param env: The environment variables to pass to the process that will get spawned. See L{twisted.internet.interfaces.IReactorProcess.spawnProcess} for more information about environments and process creation. @type request: L{twisted.web.http.Request} @param request: An HTTP request. @type qargs: A L{list} of L{str} @param qargs: The command line arguments to pass to the process that will get spawned. """ p = CGIProcessProtocol(request) self._reactor.spawnProcess(p, self.filename, [self.filename] + qargs, env, os.path.dirname(self.filename))
Run the cgi script. @type env: A L{dict} of L{str}, or L{None} @param env: The environment variables to pass to the process that will get spawned. See L{twisted.internet.interfaces.IReactorProcess.spawnProcess} for more information about environments and process creation. @type request: L{twisted.web.http.Request} @param request: An HTTP request. @type qargs: A L{list} of L{str} @param qargs: The command line arguments to pass to the process that will get spawned.
runProcess
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py
MIT
def runProcess(self, env, request, qargs=[]): """ Run a script through the C{filter} executable. @type env: A L{dict} of L{str}, or L{None} @param env: The environment variables to pass to the process that will get spawned. See L{twisted.internet.interfaces.IReactorProcess.spawnProcess} for more information about environments and process creation. @type request: L{twisted.web.http.Request} @param request: An HTTP request. @type qargs: A L{list} of L{str} @param qargs: The command line arguments to pass to the process that will get spawned. """ p = CGIProcessProtocol(request) self._reactor.spawnProcess(p, self.filter, [self.filter, self.filename] + qargs, env, os.path.dirname(self.filename))
Run a script through the C{filter} executable. @type env: A L{dict} of L{str}, or L{None} @param env: The environment variables to pass to the process that will get spawned. See L{twisted.internet.interfaces.IReactorProcess.spawnProcess} for more information about environments and process creation. @type request: L{twisted.web.http.Request} @param request: An HTTP request. @type qargs: A L{list} of L{str} @param qargs: The command line arguments to pass to the process that will get spawned.
runProcess
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py
MIT
def outReceived(self, output): """ Handle a chunk of input """ # First, make sure that the headers from the script are sorted # out (we'll want to do some parsing on these later.) if self.handling_headers: text = self.headertext + output headerEnds = [] for delimiter in b'\n\n', b'\r\n\r\n', b'\r\r', b'\n\r\n': headerend = text.find(delimiter) if headerend != -1: headerEnds.append((headerend, delimiter)) if headerEnds: # The script is entirely in control of response headers; # disable the default Content-Type value normally provided by # twisted.web.server.Request. self.request.defaultContentType = None headerEnds.sort() headerend, delimiter = headerEnds[0] self.headertext = text[:headerend] # This is a final version of the header text. linebreak = delimiter[:len(delimiter)//2] headers = self.headertext.split(linebreak) for header in headers: br = header.find(b': ') if br == -1: self._log.error( 'ignoring malformed CGI header: {header!r}', header=header) else: headerName = header[:br].lower() headerText = header[br+2:] if headerName == b'location': self.request.setResponseCode(http.FOUND) if headerName == b'status': try: # "XXX <description>" sometimes happens. statusNum = int(headerText[:3]) except: self._log.error("malformed status header") else: self.request.setResponseCode(statusNum) else: # Don't allow the application to control # these required headers. if headerName.lower() not in (b'server', b'date'): self.request.responseHeaders.addRawHeader( headerName, headerText) output = text[headerend+len(delimiter):] self.handling_headers = 0 if self.handling_headers: self.headertext = text if not self.handling_headers: self.request.write(output)
Handle a chunk of input
outReceived
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/twcgi.py
MIT
def withRequest(f): """ Decorator to cause the request to be passed as the first argument to the method. If an I{xmlrpc_} method is wrapped with C{withRequest}, the request object is passed as the first argument to that method. For example:: @withRequest def xmlrpc_echo(self, request, s): return s @since: 10.2 """ f.withRequest = True return f
Decorator to cause the request to be passed as the first argument to the method. If an I{xmlrpc_} method is wrapped with C{withRequest}, the request object is passed as the first argument to that method. For example:: @withRequest def xmlrpc_echo(self, request, s): return s @since: 10.2
withRequest
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def lookupProcedure(self, procedurePath): """ Given a string naming a procedure, return a callable object for that procedure or raise NoSuchFunction. The returned object will be called, and should return the result of the procedure, a Deferred, or a Fault instance. Override in subclasses if you want your own policy. The base implementation that given C{'foo'}, C{self.xmlrpc_foo} will be returned. If C{procedurePath} contains C{self.separator}, the sub-handler for the initial prefix is used to search for the remaining path. If you override C{lookupProcedure}, you may also want to override C{listProcedures} to accurately report the procedures supported by your resource, so that clients using the I{system.listMethods} procedure receive accurate results. @since: 11.1 """ if procedurePath.find(self.separator) != -1: prefix, procedurePath = procedurePath.split(self.separator, 1) handler = self.getSubHandler(prefix) if handler is None: raise NoSuchFunction(self.NOT_FOUND, "no such subHandler %s" % prefix) return handler.lookupProcedure(procedurePath) f = getattr(self, "xmlrpc_%s" % procedurePath, None) if not f: raise NoSuchFunction(self.NOT_FOUND, "procedure %s not found" % procedurePath) elif not callable(f): raise NoSuchFunction(self.NOT_FOUND, "procedure %s not callable" % procedurePath) else: return f
Given a string naming a procedure, return a callable object for that procedure or raise NoSuchFunction. The returned object will be called, and should return the result of the procedure, a Deferred, or a Fault instance. Override in subclasses if you want your own policy. The base implementation that given C{'foo'}, C{self.xmlrpc_foo} will be returned. If C{procedurePath} contains C{self.separator}, the sub-handler for the initial prefix is used to search for the remaining path. If you override C{lookupProcedure}, you may also want to override C{listProcedures} to accurately report the procedures supported by your resource, so that clients using the I{system.listMethods} procedure receive accurate results. @since: 11.1
lookupProcedure
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def listProcedures(self): """ Return a list of the names of all xmlrpc procedures. @since: 11.1 """ return reflect.prefixedMethodNames(self.__class__, 'xmlrpc_')
Return a list of the names of all xmlrpc procedures. @since: 11.1
listProcedures
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def __init__(self, parent): """ Implement Introspection support for an XMLRPC server. @param parent: the XMLRPC server to add Introspection support to. @type parent: L{XMLRPC} """ XMLRPC.__init__(self) self._xmlrpc_parent = parent
Implement Introspection support for an XMLRPC server. @param parent: the XMLRPC server to add Introspection support to. @type parent: L{XMLRPC}
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def xmlrpc_listMethods(self): """ Return a list of the method names implemented by this server. """ functions = [] todo = [(self._xmlrpc_parent, '')] while todo: obj, prefix = todo.pop(0) functions.extend([prefix + name for name in obj.listProcedures()]) todo.extend([ (obj.getSubHandler(name), prefix + name + obj.separator) for name in obj.getSubHandlerPrefixes() ]) return functions
Return a list of the method names implemented by this server.
xmlrpc_listMethods
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def xmlrpc_methodHelp(self, method): """ Return a documentation string describing the use of the given method. """ method = self._xmlrpc_parent.lookupProcedure(method) return (getattr(method, 'help', None) or getattr(method, '__doc__', None) or '')
Return a documentation string describing the use of the given method.
xmlrpc_methodHelp
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def xmlrpc_methodSignature(self, method): """ Return a list of type signatures. Each type signature is a list of the form [rtype, type1, type2, ...] where rtype is the return type and typeN is the type of the Nth argument. If no signature information is available, the empty string is returned. """ method = self._xmlrpc_parent.lookupProcedure(method) return getattr(method, 'signature', None) or ''
Return a list of type signatures. Each type signature is a list of the form [rtype, type1, type2, ...] where rtype is the return type and typeN is the type of the Nth argument. If no signature information is available, the empty string is returned.
xmlrpc_methodSignature
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def addIntrospection(xmlrpc): """ Add Introspection support to an XMLRPC server. @param parent: the XMLRPC server to add Introspection support to. @type parent: L{XMLRPC} """ xmlrpc.putSubHandler('system', XMLRPCIntrospection(xmlrpc))
Add Introspection support to an XMLRPC server. @param parent: the XMLRPC server to add Introspection support to. @type parent: L{XMLRPC}
addIntrospection
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def handleResponse(self, contents): """ Handle the XML-RPC response received from the server. Specifically, disconnect from the server and store the XML-RPC response so that it can be properly handled when the disconnect is finished. """ self.transport.loseConnection() self._response = contents
Handle the XML-RPC response received from the server. Specifically, disconnect from the server and store the XML-RPC response so that it can be properly handled when the disconnect is finished.
handleResponse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def connectionLost(self, reason): """ The connection to the server has been lost. If we have a full response from the server, then parse it and fired a Deferred with the return value or C{Fault} that the server gave us. """ http.HTTPClient.connectionLost(self, reason) if self._response is not None: response, self._response = self._response, None self.factory.parseResponse(response)
The connection to the server has been lost. If we have a full response from the server, then parse it and fired a Deferred with the return value or C{Fault} that the server gave us.
connectionLost
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def __init__(self, path, host, method, user=None, password=None, allowNone=False, args=(), canceller=None, useDateTime=False): """ @param method: The name of the method to call. @type method: C{str} @param allowNone: allow the use of None values in parameters. It's passed to the underlying xmlrpclib implementation. Defaults to C{False}. @type allowNone: C{bool} or L{None} @param args: the arguments to pass to the method. @type args: C{tuple} @param canceller: A 1-argument callable passed to the deferred as the canceller callback. @type canceller: callable or L{None} """ self.path, self.host = path, host self.user, self.password = user, password self.payload = payloadTemplate % (method, xmlrpclib.dumps(args, allow_none=allowNone)) if isinstance(self.payload, unicode): self.payload = self.payload.encode('utf8') self.deferred = defer.Deferred(canceller) self.useDateTime = useDateTime
@param method: The name of the method to call. @type method: C{str} @param allowNone: allow the use of None values in parameters. It's passed to the underlying xmlrpclib implementation. Defaults to C{False}. @type allowNone: C{bool} or L{None} @param args: the arguments to pass to the method. @type args: C{tuple} @param canceller: A 1-argument callable passed to the deferred as the canceller callback. @type canceller: callable or L{None}
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def __init__(self, url, user=None, password=None, allowNone=False, useDateTime=False, connectTimeout=30.0, reactor=reactor): """ @param url: The URL to which to post method calls. Calls will be made over SSL if the scheme is HTTPS. If netloc contains username or password information, these will be used to authenticate, as long as the C{user} and C{password} arguments are not specified. @type url: L{bytes} """ scheme, netloc, path, params, query, fragment = urllib_parse.urlparse( url) netlocParts = netloc.split(b'@') if len(netlocParts) == 2: userpass = netlocParts.pop(0).split(b':') self.user = userpass.pop(0) try: self.password = userpass.pop(0) except: self.password = None else: self.user = self.password = None hostport = netlocParts[0].split(b':') self.host = hostport.pop(0) try: self.port = int(hostport.pop(0)) except: self.port = None self.path = path if self.path in [b'', None]: self.path = b'/' self.secure = (scheme == b'https') if user is not None: self.user = user if password is not None: self.password = password self.allowNone = allowNone self.useDateTime = useDateTime self.connectTimeout = connectTimeout self._reactor = reactor
@param url: The URL to which to post method calls. Calls will be made over SSL if the scheme is HTTPS. If netloc contains username or password information, these will be used to authenticate, as long as the C{user} and C{password} arguments are not specified. @type url: L{bytes}
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def callRemote(self, method, *args): """ Call remote XML-RPC C{method} with given arguments. @return: a L{defer.Deferred} that will fire with the method response, or a failure if the method failed. Generally, the failure type will be L{Fault}, but you can also have an C{IndexError} on some buggy servers giving empty responses. If the deferred is cancelled before the request completes, the connection is closed and the deferred will fire with a L{defer.CancelledError}. """ def cancel(d): factory.deferred = None connector.disconnect() factory = self.queryFactory( self.path, self.host, method, self.user, self.password, self.allowNone, args, cancel, self.useDateTime) if self.secure: from twisted.internet import ssl connector = self._reactor.connectSSL( nativeString(self.host), self.port or 443, factory, ssl.ClientContextFactory(), timeout=self.connectTimeout) else: connector = self._reactor.connectTCP( nativeString(self.host), self.port or 80, factory, timeout=self.connectTimeout) return factory.deferred
Call remote XML-RPC C{method} with given arguments. @return: a L{defer.Deferred} that will fire with the method response, or a failure if the method failed. Generally, the failure type will be L{Fault}, but you can also have an C{IndexError} on some buggy servers giving empty responses. If the deferred is cancelled before the request completes, the connection is closed and the deferred will fire with a L{defer.CancelledError}.
callRemote
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/xmlrpc.py
MIT
def _PRE(text): """ Wraps <pre> tags around some text and HTML-escape it. This is here since once twisted.web.html was deprecated it was hard to migrate the html.PRE from current code to twisted.web.template. For new code consider using twisted.web.template. @return: Escaped text wrapped in <pre> tags. @rtype: C{str} """ return '<pre>%s</pre>' % (escape(text),)
Wraps <pre> tags around some text and HTML-escape it. This is here since once twisted.web.html was deprecated it was hard to migrate the html.PRE from current code to twisted.web.template. For new code consider using twisted.web.template. @return: Escaped text wrapped in <pre> tags. @rtype: C{str}
_PRE
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def redirectTo(URL, request): """ Generate a redirect to the given location. @param URL: A L{bytes} giving the location to which to redirect. @type URL: L{bytes} @param request: The request object to use to generate the redirect. @type request: L{IRequest<twisted.web.iweb.IRequest>} provider @raise TypeError: If the type of C{URL} a L{unicode} instead of L{bytes}. @return: A C{bytes} containing HTML which tries to convince the client agent to visit the new location even if it doesn't respect the I{FOUND} response code. This is intended to be returned from a render method, eg:: def render_GET(self, request): return redirectTo(b"http://example.com/", request) """ if isinstance(URL, unicode) : raise TypeError("Unicode object not allowed as URL") request.setHeader(b"Content-Type", b"text/html; charset=utf-8") request.redirect(URL) content = """ <html> <head> <meta http-equiv=\"refresh\" content=\"0;URL=%(url)s\"> </head> <body bgcolor=\"#FFFFFF\" text=\"#000000\"> <a href=\"%(url)s\">click here</a> </body> </html> """ % {'url': nativeString(URL)} if _PY3: content = content.encode("utf8") return content
Generate a redirect to the given location. @param URL: A L{bytes} giving the location to which to redirect. @type URL: L{bytes} @param request: The request object to use to generate the redirect. @type request: L{IRequest<twisted.web.iweb.IRequest>} provider @raise TypeError: If the type of C{URL} a L{unicode} instead of L{bytes}. @return: A C{bytes} containing HTML which tries to convince the client agent to visit the new location even if it doesn't respect the I{FOUND} response code. This is intended to be returned from a render method, eg:: def render_GET(self, request): return redirectTo(b"http://example.com/", request)
redirectTo
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def sourceLine(self, request, tag): """ Render the line of source as a child of C{tag}. """ return tag(self.source.replace(' ', u' \N{NO-BREAK SPACE}'))
Render the line of source as a child of C{tag}.
sourceLine
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def lineNumber(self, request, tag): """ Render the line number as a child of C{tag}. """ return tag(str(self.number))
Render the line number as a child of C{tag}.
lineNumber
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def _getSourceLines(self): """ Find the source line references by C{self.frame} and yield, in source line order, it and the previous and following lines. @return: A generator which yields two-tuples. Each tuple gives a source line number and the contents of that source line. """ filename = self.frame[1] lineNumber = self.frame[2] for snipLineNumber in range(lineNumber - 1, lineNumber + 2): yield (snipLineNumber, linecache.getline(filename, snipLineNumber).rstrip())
Find the source line references by C{self.frame} and yield, in source line order, it and the previous and following lines. @return: A generator which yields two-tuples. Each tuple gives a source line number and the contents of that source line.
_getSourceLines
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def sourceLines(self, request, tag): """ Render the source line indicated by C{self.frame} and several surrounding lines. The active line will be given a I{class} of C{"snippetHighlightLine"}. Other lines will be given a I{class} of C{"snippetLine"}. """ for (lineNumber, sourceLine) in self._getSourceLines(): newTag = tag.clone() if lineNumber == self.frame[2]: cssClass = "snippetHighlightLine" else: cssClass = "snippetLine" loader = TagLoader(newTag(**{"class": cssClass})) yield _SourceLineElement(loader, lineNumber, sourceLine)
Render the source line indicated by C{self.frame} and several surrounding lines. The active line will be given a I{class} of C{"snippetHighlightLine"}. Other lines will be given a I{class} of C{"snippetLine"}.
sourceLines
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def filename(self, request, tag): """ Render the name of the file this frame references as a child of C{tag}. """ return tag(self.frame[1])
Render the name of the file this frame references as a child of C{tag}.
filename
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def lineNumber(self, request, tag): """ Render the source line number this frame references as a child of C{tag}. """ return tag(str(self.frame[2]))
Render the source line number this frame references as a child of C{tag}.
lineNumber
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def function(self, request, tag): """ Render the function name this frame references as a child of C{tag}. """ return tag(self.frame[0])
Render the function name this frame references as a child of C{tag}.
function
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def source(self, request, tag): """ Render the source code surrounding the line this frame references, replacing C{tag}. """ return _SourceFragmentElement(TagLoader(tag), self.frame)
Render the source code surrounding the line this frame references, replacing C{tag}.
source
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def frames(self, request, tag): """ Render the list of frames in this L{_StackElement}, replacing C{tag}. """ return [ _FrameElement(TagLoader(tag.clone()), frame) for frame in self.stackFrames]
Render the list of frames in this L{_StackElement}, replacing C{tag}.
frames
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def type(self, request, tag): """ Render the exception type as a child of C{tag}. """ return tag(fullyQualifiedName(self.failure.type))
Render the exception type as a child of C{tag}.
type
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def value(self, request, tag): """ Render the exception value as a child of C{tag}. """ return tag(unicode(self.failure.value).encode('utf8'))
Render the exception value as a child of C{tag}.
value
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def traceback(self, request, tag): """ Render all the frames in the wrapped L{Failure<twisted.python.failure.Failure>}'s traceback stack, replacing C{tag}. """ return _StackElement(TagLoader(tag), self.failure.frames)
Render all the frames in the wrapped L{Failure<twisted.python.failure.Failure>}'s traceback stack, replacing C{tag}.
traceback
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def formatFailure(myFailure): """ Construct an HTML representation of the given failure. Consider using L{FailureElement} instead. @type myFailure: L{Failure<twisted.python.failure.Failure>} @rtype: C{bytes} @return: A string containing the HTML representation of the given failure. """ result = [] flattenString(None, FailureElement(myFailure)).addBoth(result.append) if isinstance(result[0], bytes): # Ensure the result string is all ASCII, for compatibility with the # default encoding expected by browsers. return result[0].decode('utf-8').encode('ascii', 'xmlcharrefreplace') result[0].raiseException()
Construct an HTML representation of the given failure. Consider using L{FailureElement} instead. @type myFailure: L{Failure<twisted.python.failure.Failure>} @rtype: C{bytes} @return: A string containing the HTML representation of the given failure.
formatFailure
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/util.py
MIT
def alias(aliasPath, sourcePath): """ I am not a very good aliaser. But I'm the best I can be. If I'm aliasing to a Resource that generates links, and it uses any parts of request.prepath to do so, the links will not be relative to the aliased path, but rather to the aliased-to path. That I can't alias static.File directory listings that nicely. However, I can still be useful, as many resources will play nice. """ sourcePath = sourcePath.split('/') aliasPath = aliasPath.split('/') def rewriter(request): if request.postpath[:len(aliasPath)] == aliasPath: after = request.postpath[len(aliasPath):] request.postpath = sourcePath + after request.path = '/'+'/'.join(request.prepath+request.postpath) return rewriter
I am not a very good aliaser. But I'm the best I can be. If I'm aliasing to a Resource that generates links, and it uses any parts of request.prepath to do so, the links will not be relative to the aliased path, but rather to the aliased-to path. That I can't alias static.File directory listings that nicely. However, I can still be useful, as many resources will play nice.
alias
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/rewrite.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/rewrite.py
MIT
def getElementsByTagName(iNode, name): """ Return a list of all child elements of C{iNode} with a name matching C{name}. Note that this implementation does not conform to the DOM Level 1 Core specification because it may return C{iNode}. @param iNode: An element at which to begin searching. If C{iNode} has a name matching C{name}, it will be included in the result. @param name: A C{str} giving the name of the elements to return. @return: A C{list} of direct or indirect child elements of C{iNode} with the name C{name}. This may include C{iNode}. """ matches = [] matches_append = matches.append # faster lookup. don't do this at home slice = [iNode] while len(slice) > 0: c = slice.pop(0) if c.nodeName == name: matches_append(c) slice[:0] = c.childNodes return matches
Return a list of all child elements of C{iNode} with a name matching C{name}. Note that this implementation does not conform to the DOM Level 1 Core specification because it may return C{iNode}. @param iNode: An element at which to begin searching. If C{iNode} has a name matching C{name}, it will be included in the result. @param name: A C{str} giving the name of the elements to return. @return: A C{list} of direct or indirect child elements of C{iNode} with the name C{name}. This may include C{iNode}.
getElementsByTagName
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def unescape(text, chars=REV_HTML_ESCAPE_CHARS): """ Perform the exact opposite of 'escape'. """ for s, h in chars: text = text.replace(h, s) return text
Perform the exact opposite of 'escape'.
unescape
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def escape(text, chars=HTML_ESCAPE_CHARS): """ Escape a few XML special chars with XML entities. """ for s, h in chars: text = text.replace(s, h) return text
Escape a few XML special chars with XML entities.
escape
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def isEqualToNode(self, other): """ Compare this node to C{other}. If the nodes have the same number of children and corresponding children are equal to each other, return C{True}, otherwise return C{False}. @type other: L{Node} @rtype: C{bool} """ if len(self.childNodes) != len(other.childNodes): return False for a, b in zip(self.childNodes, other.childNodes): if not a.isEqualToNode(b): return False return True
Compare this node to C{other}. If the nodes have the same number of children and corresponding children are equal to each other, return C{True}, otherwise return C{False}. @type other: L{Node} @rtype: C{bool}
isEqualToNode
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def appendChild(self, child): """ Make the given L{Node} the last child of this node. @param child: The L{Node} which will become a child of this node. @raise TypeError: If C{child} is not a C{Node} instance. """ if not isinstance(child, Node): raise TypeError("expected Node instance") self.childNodes.append(child) child.parentNode = self
Make the given L{Node} the last child of this node. @param child: The L{Node} which will become a child of this node. @raise TypeError: If C{child} is not a C{Node} instance.
appendChild
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def insertBefore(self, new, ref): """ Make the given L{Node} C{new} a child of this node which comes before the L{Node} C{ref}. @param new: A L{Node} which will become a child of this node. @param ref: A L{Node} which is already a child of this node which C{new} will be inserted before. @raise TypeError: If C{new} or C{ref} is not a C{Node} instance. @return: C{new} """ if not isinstance(new, Node) or not isinstance(ref, Node): raise TypeError("expected Node instance") i = self.childNodes.index(ref) new.parentNode = self self.childNodes.insert(i, new) return new
Make the given L{Node} C{new} a child of this node which comes before the L{Node} C{ref}. @param new: A L{Node} which will become a child of this node. @param ref: A L{Node} which is already a child of this node which C{new} will be inserted before. @raise TypeError: If C{new} or C{ref} is not a C{Node} instance. @return: C{new}
insertBefore
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def removeChild(self, child): """ Remove the given L{Node} from this node's children. @param child: A L{Node} which is a child of this node which will no longer be a child of this node after this method is called. @raise TypeError: If C{child} is not a C{Node} instance. @return: C{child} """ if not isinstance(child, Node): raise TypeError("expected Node instance") if child in self.childNodes: self.childNodes.remove(child) child.parentNode = None return child
Remove the given L{Node} from this node's children. @param child: A L{Node} which is a child of this node which will no longer be a child of this node after this method is called. @raise TypeError: If C{child} is not a C{Node} instance. @return: C{child}
removeChild
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def replaceChild(self, newChild, oldChild): """ Replace a L{Node} which is already a child of this node with a different node. @param newChild: A L{Node} which will be made a child of this node. @param oldChild: A L{Node} which is a child of this node which will give up its position to C{newChild}. @raise TypeError: If C{newChild} or C{oldChild} is not a C{Node} instance. @raise ValueError: If C{oldChild} is not a child of this C{Node}. """ if not isinstance(newChild, Node) or not isinstance(oldChild, Node): raise TypeError("expected Node instance") if oldChild.parentNode is not self: raise ValueError("oldChild is not a child of this node") self.childNodes[self.childNodes.index(oldChild)] = newChild oldChild.parentNode = None newChild.parentNode = self
Replace a L{Node} which is already a child of this node with a different node. @param newChild: A L{Node} which will be made a child of this node. @param oldChild: A L{Node} which is a child of this node which will give up its position to C{newChild}. @raise TypeError: If C{newChild} or C{oldChild} is not a C{Node} instance. @raise ValueError: If C{oldChild} is not a child of this C{Node}.
replaceChild
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def appendChild(self, child): """ Make the given L{Node} the I{document element} of this L{Document}. @param child: The L{Node} to make into this L{Document}'s document element. @raise ValueError: If this document already has a document element. """ if self.childNodes: raise ValueError("Only one element per document.") Node.appendChild(self, child)
Make the given L{Node} the I{document element} of this L{Document}. @param child: The L{Node} to make into this L{Document}'s document element. @raise ValueError: If this document already has a document element.
appendChild
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def isEqualToNode(self, other): """ Compare this text to C{text}. If the underlying values and the C{raw} flag are the same, return C{True}, otherwise return C{False}. """ return ( CharacterData.isEqualToNode(self, other) and self.raw == other.raw)
Compare this text to C{text}. If the underlying values and the C{raw} flag are the same, return C{True}, otherwise return C{False}.
isEqualToNode
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def isEqualToNode(self, other): """ Compare this element to C{other}. If the C{nodeName}, C{namespace}, C{attributes}, and C{childNodes} are all the same, return C{True}, otherwise return C{False}. """ return ( self.nodeName.lower() == other.nodeName.lower() and self.namespace == other.namespace and self.attributes == other.attributes and Node.isEqualToNode(self, other))
Compare this element to C{other}. If the C{nodeName}, C{namespace}, C{attributes}, and C{childNodes} are all the same, return C{True}, otherwise return C{False}.
isEqualToNode
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def writexml(self, stream, indent='', addindent='', newl='', strip=0, nsprefixes={}, namespace=''): """ Serialize this L{Element} to the given stream. @param stream: A file-like object to which this L{Element} will be written. @param nsprefixes: A C{dict} mapping namespace URIs as C{str} to prefixes as C{str}. This defines the prefixes which are already in scope in the document at the point at which this L{Element} exists. This is essentially an implementation detail for namespace support. Applications should not try to use it. @param namespace: The namespace URI as a C{str} which is the default at the point in the document at which this L{Element} exists. This is essentially an implementation detail for namespace support. Applications should not try to use it. """ # write beginning ALLOWSINGLETON = ('img', 'br', 'hr', 'base', 'meta', 'link', 'param', 'area', 'input', 'col', 'basefont', 'isindex', 'frame') BLOCKELEMENTS = ('html', 'head', 'body', 'noscript', 'ins', 'del', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'script', 'ul', 'ol', 'dl', 'pre', 'hr', 'blockquote', 'address', 'p', 'div', 'fieldset', 'table', 'tr', 'form', 'object', 'fieldset', 'applet', 'map') FORMATNICELY = ('tr', 'ul', 'ol', 'head') # this should never be necessary unless people start # changing .tagName on the fly(?) if not self.preserveCase: self.endTagName = self.tagName w = _streamWriteWrapper(stream) if self.nsprefixes: newprefixes = self.nsprefixes.copy() for ns in nsprefixes.keys(): if ns in newprefixes: del newprefixes[ns] else: newprefixes = {} begin = ['<'] if self.tagName in BLOCKELEMENTS: begin = [newl, indent] + begin bext = begin.extend writeattr = lambda _atr, _val: bext((' ', _atr, '="', escape(_val), '"')) # Make a local for tracking what end tag will be used. If namespace # prefixes are involved, this will be changed to account for that # before it's actually used. endTagName = self.endTagName if namespace != self.namespace and self.namespace is not None: # If the current default namespace is not the namespace of this tag # (and this tag has a namespace at all) then we'll write out # something related to namespaces. if self.namespace in nsprefixes: # This tag's namespace already has a prefix bound to it. Use # that prefix. prefix = nsprefixes[self.namespace] bext(prefix + ':' + self.tagName) # Also make sure we use it for the end tag. endTagName = prefix + ':' + self.endTagName else: # This tag's namespace has no prefix bound to it. Change the # default namespace to this tag's namespace so we don't need # prefixes. Alternatively, we could add a new prefix binding. # I'm not sure why the code was written one way rather than the # other. -exarkun bext(self.tagName) writeattr("xmlns", self.namespace) # The default namespace just changed. Make sure any children # know about this. namespace = self.namespace else: # This tag has no namespace or its namespace is already the default # namespace. Nothing extra to do here. bext(self.tagName) j = ''.join for attr, val in sorted(self.attributes.items()): if isinstance(attr, tuple): ns, key = attr if ns in nsprefixes: prefix = nsprefixes[ns] else: prefix = next(genprefix) newprefixes[ns] = prefix assert val is not None writeattr(prefix + ':' + key, val) else: assert val is not None writeattr(attr, val) if newprefixes: for ns, prefix in iteritems(newprefixes): if prefix: writeattr('xmlns:'+prefix, ns) newprefixes.update(nsprefixes) downprefixes = newprefixes else: downprefixes = nsprefixes w(j(begin)) if self.childNodes: w(">") newindent = indent + addindent for child in self.childNodes: if self.tagName in BLOCKELEMENTS and \ self.tagName in FORMATNICELY: w(j((newl, newindent))) child.writexml(stream, newindent, addindent, newl, strip, downprefixes, namespace) if self.tagName in BLOCKELEMENTS: w(j((newl, indent))) w(j(('</', endTagName, '>'))) elif self.tagName.lower() not in ALLOWSINGLETON: w(j(('></', endTagName, '>'))) else: w(" />")
Serialize this L{Element} to the given stream. @param stream: A file-like object to which this L{Element} will be written. @param nsprefixes: A C{dict} mapping namespace URIs as C{str} to prefixes as C{str}. This defines the prefixes which are already in scope in the document at the point at which this L{Element} exists. This is essentially an implementation detail for namespace support. Applications should not try to use it. @param namespace: The namespace URI as a C{str} which is the default at the point in the document at which this L{Element} exists. This is essentially an implementation detail for namespace support. Applications should not try to use it.
writexml
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def parse(readable, *args, **kwargs): """ Parse HTML or XML readable. """ if not hasattr(readable, "read"): readable = open(readable, "rb") mdp = MicroDOMParser(*args, **kwargs) mdp.filename = getattr(readable, "name", "<xmlfile />") mdp.makeConnection(None) if hasattr(readable, "getvalue"): mdp.dataReceived(readable.getvalue()) else: r = readable.read(1024) while r: mdp.dataReceived(r) r = readable.read(1024) mdp.connectionLost(None) if not mdp.documents: raise ParseError(mdp.filename, 0, 0, "No top-level Nodes in document") if mdp.beExtremelyLenient: if len(mdp.documents) == 1: d = mdp.documents[0] if not isinstance(d, Element): el = Element("html") el.appendChild(d) d = el else: d = Element("html") for child in mdp.documents: d.appendChild(child) else: d = mdp.documents[0] doc = Document(d) doc.doctype = mdp._mddoctype return doc
Parse HTML or XML readable.
parse
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def parseXML(readable): """ Parse an XML readable object. """ return parse(readable, caseInsensitive=0, preserveCase=1)
Parse an XML readable object.
parseXML
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py
MIT
def opt_port(self, port): """ (DEPRECATED: use --listen) Strports description of port to start the server on """ msg = deprecate.getDeprecationWarningString( self.opt_port, incremental.Version('Twisted', 18, 4, 0)) warnings.warn(msg, category=DeprecationWarning, stacklevel=2) self['port'] = port
(DEPRECATED: use --listen) Strports description of port to start the server on
opt_port
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_https(self, port): """ (DEPRECATED: use --listen) Port to listen on for Secure HTTP. """ msg = deprecate.getDeprecationWarningString( self.opt_https, incremental.Version('Twisted', 18, 4, 0)) warnings.warn(msg, category=DeprecationWarning, stacklevel=2) self['https'] = port
(DEPRECATED: use --listen) Port to listen on for Secure HTTP.
opt_https
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_listen(self, port): """ Add an strports description of port to start the server on. [default: tcp:8080] """ self['ports'].append(port)
Add an strports description of port to start the server on. [default: tcp:8080]
opt_listen
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_index(self, indexName): """ Add the name of a file used to check for directory indexes. [default: index, index.html] """ self['indexes'].append(indexName)
Add the name of a file used to check for directory indexes. [default: index, index.html]
opt_index
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_user(self): """ Makes a server with ~/public_html and ~/.twistd-web-pb support for users. """ self['root'] = distrib.UserDirectory()
Makes a server with ~/public_html and ~/.twistd-web-pb support for users.
opt_user
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_path(self, path): """ <path> is either a specific file or a directory to be set as the root of the web server. Use this if you have a directory full of HTML, cgi, epy, or rpy files or any other files that you want to be served up raw. """ self['root'] = static.File(os.path.abspath(path)) self['root'].processors = { '.epy': script.PythonScript, '.rpy': script.ResourceScript, } self['root'].processors['.cgi'] = twcgi.CGIScript
<path> is either a specific file or a directory to be set as the root of the web server. Use this if you have a directory full of HTML, cgi, epy, or rpy files or any other files that you want to be served up raw.
opt_path
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_processor(self, proc): """ `ext=class' where `class' is added as a Processor for files ending with `ext'. """ if not isinstance(self['root'], static.File): raise usage.UsageError( "You can only use --processor after --path.") ext, klass = proc.split('=', 1) self['root'].processors[ext] = reflect.namedClass(klass)
`ext=class' where `class' is added as a Processor for files ending with `ext'.
opt_processor
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_class(self, className): """ Create a Resource subclass with a zero-argument constructor. """ classObj = reflect.namedClass(className) self['root'] = classObj()
Create a Resource subclass with a zero-argument constructor.
opt_class
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_resource_script(self, name): """ An .rpy file to be used as the root resource of the webserver. """ self['root'] = script.ResourceScriptWrapper(name)
An .rpy file to be used as the root resource of the webserver.
opt_resource_script
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_wsgi(self, name): """ The FQPN of a WSGI application object to serve as the root resource of the webserver. """ try: application = reflect.namedAny(name) except (AttributeError, ValueError): raise usage.UsageError("No such WSGI application: %r" % (name,)) pool = threadpool.ThreadPool() reactor.callWhenRunning(pool.start) reactor.addSystemEventTrigger('after', 'shutdown', pool.stop) self['root'] = wsgi.WSGIResource(reactor, pool, application)
The FQPN of a WSGI application object to serve as the root resource of the webserver.
opt_wsgi
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_mime_type(self, defaultType): """ Specify the default mime-type for static files. """ if not isinstance(self['root'], static.File): raise usage.UsageError( "You can only use --mime_type after --path.") self['root'].defaultType = defaultType
Specify the default mime-type for static files.
opt_mime_type
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_allow_ignore_ext(self): """ Specify whether or not a request for 'foo' should return 'foo.ext' """ if not isinstance(self['root'], static.File): raise usage.UsageError("You can only use --allow_ignore_ext " "after --path.") self['root'].ignoreExt('*')
Specify whether or not a request for 'foo' should return 'foo.ext'
opt_allow_ignore_ext
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_ignore_ext(self, ext): """ Specify an extension to ignore. These will be processed in order. """ if not isinstance(self['root'], static.File): raise usage.UsageError("You can only use --ignore_ext " "after --path.") self['root'].ignoreExt(ext)
Specify an extension to ignore. These will be processed in order.
opt_ignore_ext
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def opt_add_header(self, header): """ Specify an additional header to be included in all responses. Specified as "HeaderName: HeaderValue". """ name, value = header.split(':', 1) self['extraHeaders'].append((name.strip(), value.strip()))
Specify an additional header to be included in all responses. Specified as "HeaderName: HeaderValue".
opt_add_header
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def postOptions(self): """ Set up conditional defaults and check for dependencies. If SSL is not available but an HTTPS server was configured, raise a L{UsageError} indicating that this is not possible. If no server port was supplied, select a default appropriate for the other options supplied. """ if self['port'] is not None: self['ports'].append(self['port']) if self['https'] is not None: try: reflect.namedModule('OpenSSL.SSL') except ImportError: raise usage.UsageError("SSL support not installed") sslStrport = 'ssl:port={}:privateKey={}:certKey={}'.format( self['https'], self['privkey'], self['certificate'], ) self['ports'].append(sslStrport) if len(self['ports']) == 0: if self['personal']: path = os.path.expanduser( os.path.join('~', distrib.UserDirectory.userSocketName)) self['ports'].append('unix:' + path) else: self['ports'].append('tcp:8080')
Set up conditional defaults and check for dependencies. If SSL is not available but an HTTPS server was configured, raise a L{UsageError} indicating that this is not possible. If no server port was supplied, select a default appropriate for the other options supplied.
postOptions
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def makePersonalServerFactory(site): """ Create and return a factory which will respond to I{distrib} requests against the given site. @type site: L{twisted.web.server.Site} @rtype: L{twisted.internet.protocol.Factory} """ return pb.PBServerFactory(distrib.ResourcePublisher(site))
Create and return a factory which will respond to I{distrib} requests against the given site. @type site: L{twisted.web.server.Site} @rtype: L{twisted.internet.protocol.Factory}
makePersonalServerFactory
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py
MIT
def getChallenge(self, request): """ Return a challenge including the HTTP authentication realm with which this factory was created. """ return {'realm': self.authenticationRealm}
Return a challenge including the HTTP authentication realm with which this factory was created.
getChallenge
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/basic.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/basic.py
MIT
def decode(self, response, request): """ Parse the base64-encoded, colon-separated username and password into a L{credentials.UsernamePassword} instance. """ try: creds = binascii.a2b_base64(response + b'===') except binascii.Error: raise error.LoginFailed('Invalid credentials') creds = creds.split(b':', 1) if len(creds) == 2: return credentials.UsernamePassword(*creds) else: raise error.LoginFailed('Invalid credentials')
Parse the base64-encoded, colon-separated username and password into a L{credentials.UsernamePassword} instance.
decode
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/basic.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/basic.py
MIT
def render(self, request): """ Send www-authenticate headers to the client """ def ensureBytes(s): return s.encode('ascii') if isinstance(s, unicode) else s def generateWWWAuthenticate(scheme, challenge): l = [] for k, v in challenge.items(): k = ensureBytes(k) v = ensureBytes(v) l.append(k + b"=" + quoteString(v)) return b" ".join([scheme, b", ".join(l)]) def quoteString(s): return b'"' + s.replace(b'\\', b'\\\\').replace(b'"', b'\\"') + b'"' request.setResponseCode(401) for fact in self._credentialFactories: challenge = fact.getChallenge(request) request.responseHeaders.addRawHeader( b'www-authenticate', generateWWWAuthenticate(fact.scheme, challenge)) if request.method == b'HEAD': return b'' return b'Unauthorized'
Send www-authenticate headers to the client
render
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
MIT
def getChildWithDefault(self, path, request): """ Disable resource dispatch """ return self
Disable resource dispatch
getChildWithDefault
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
MIT
def __init__(self, portal, credentialFactories): """ Initialize a session wrapper @type portal: C{Portal} @param portal: The portal that will authenticate the remote client @type credentialFactories: C{Iterable} @param credentialFactories: The portal that will authenticate the remote client based on one submitted C{ICredentialFactory} """ self._portal = portal self._credentialFactories = credentialFactories
Initialize a session wrapper @type portal: C{Portal} @param portal: The portal that will authenticate the remote client @type credentialFactories: C{Iterable} @param credentialFactories: The portal that will authenticate the remote client based on one submitted C{ICredentialFactory}
__init__
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
MIT
def _authorizedResource(self, request): """ Get the L{IResource} which the given request is authorized to receive. If the proper authorization headers are present, the resource will be requested from the portal. If not, an anonymous login attempt will be made. """ authheader = request.getHeader(b'authorization') if not authheader: return util.DeferredResource(self._login(Anonymous())) factory, respString = self._selectParseHeader(authheader) if factory is None: return UnauthorizedResource(self._credentialFactories) try: credentials = factory.decode(respString, request) except error.LoginFailed: return UnauthorizedResource(self._credentialFactories) except: self._log.failure("Unexpected failure from credentials factory") return ErrorPage(500, None, None) else: return util.DeferredResource(self._login(credentials))
Get the L{IResource} which the given request is authorized to receive. If the proper authorization headers are present, the resource will be requested from the portal. If not, an anonymous login attempt will be made.
_authorizedResource
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
MIT
def render(self, request): """ Find the L{IResource} avatar suitable for the given request, if possible, and render it. Otherwise, perhaps render an error page requiring authorization or describing an internal server failure. """ return self._authorizedResource(request).render(request)
Find the L{IResource} avatar suitable for the given request, if possible, and render it. Otherwise, perhaps render an error page requiring authorization or describing an internal server failure.
render
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
MIT
def getChildWithDefault(self, path, request): """ Inspect the Authorization HTTP header, and return a deferred which, when fired after successful authentication, will return an authorized C{Avatar}. On authentication failure, an C{UnauthorizedResource} will be returned, essentially halting further dispatch on the wrapped resource and all children """ # Don't consume any segments of the request - this class should be # transparent! request.postpath.insert(0, request.prepath.pop()) return self._authorizedResource(request)
Inspect the Authorization HTTP header, and return a deferred which, when fired after successful authentication, will return an authorized C{Avatar}. On authentication failure, an C{UnauthorizedResource} will be returned, essentially halting further dispatch on the wrapped resource and all children
getChildWithDefault
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
MIT
def _login(self, credentials): """ Get the L{IResource} avatar for the given credentials. @return: A L{Deferred} which will be called back with an L{IResource} avatar or which will errback if authentication fails. """ d = self._portal.login(credentials, None, IResource) d.addCallbacks(self._loginSucceeded, self._loginFailed) return d
Get the L{IResource} avatar for the given credentials. @return: A L{Deferred} which will be called back with an L{IResource} avatar or which will errback if authentication fails.
_login
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
MIT
def getChildWithDefault(self, name, request): """ Pass through the lookup to the wrapped resource, wrapping the result in L{ResourceWrapper} to ensure C{logout} is called when rendering of the child is complete. """ return ResourceWrapper(self.resource.getChildWithDefault(name, request))
Pass through the lookup to the wrapped resource, wrapping the result in L{ResourceWrapper} to ensure C{logout} is called when rendering of the child is complete.
_loginSucceeded.getChildWithDefault
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
MIT
def render(self, request): """ Hook into response generation so that when rendering has finished completely (with or without error), C{logout} is called. """ request.notifyFinish().addBoth(lambda ign: logout()) return super(ResourceWrapper, self).render(request)
Hook into response generation so that when rendering has finished completely (with or without error), C{logout} is called.
_loginSucceeded.render
python
wistbean/learn_python3_spider
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py
MIT