desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Handle the last unanticipated exception. (Core)'
def handle_error(self):
try: self.hooks.run('before_error_response') if self.error_response: self.error_response() self.hooks.run('after_error_response') cherrypy.serving.response.finalize() except cherrypy.HTTPRedirect: inst = sys.exc_info()[1] inst.set_response() ch...
'Collapse self.body to a single string; replace it and return it.'
def collapse_body(self):
if isinstance(self.body, basestring): return self.body newbody = [] for chunk in self.body: if (py3k and (not isinstance(chunk, bytes))): raise TypeError(("Chunk %s is not of type 'bytes'." % repr(chunk))) newbody.append(chunk) newbody = ntob('').joi...
'Transform headers (and cookies) into self.header_list. (Core)'
def finalize(self):
try: (code, reason, _) = httputil.valid_status(self.status) except ValueError: raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0]) headers = self.headers self.status = ('%s %s' % (code, reason)) self.output_status = ((ntob(str(code), 'ascii') + ntob(' ')) + headers.encode(...
'If now > self.time + self.timeout, set self.timed_out. This purposefully sets a flag, rather than raising an error, so that a monitor thread can interrupt the Response thread.'
def check_timeout(self):
if (time.time() > (self.time + self.timeout)): self.timed_out = True
'Parse the next HTTP request start-line and message-headers.'
def parse_request(self):
self.rfile = SizeCheckWrapper(self.conn.rfile, self.server.max_request_header_size) try: success = self.read_request_line() except MaxSizeExceeded: self.simple_response('414 Request-URI Too Long', 'The Request-URI sent with the request exceeds the maximum ...
'Read self.rfile into self.inheaders. Return success.'
def read_request_headers(self):
try: read_headers(self.rfile, self.inheaders) except ValueError: ex = sys.exc_info()[1] self.simple_response('400 Bad Request', ex.args[0]) return False mrbs = self.server.max_request_body_size if (mrbs and (int(self.inheaders.get('Content-Length', 0)) > mrbs)): ...
'Parse a Request-URI into (scheme, authority, path). Note that Request-URI\'s must be one of:: Request-URI = "*" | absoluteURI | abs_path | authority Therefore, a Request-URI which starts with a double forward-slash cannot be a "net_path":: net_path = "//" authority [ abs_path ] Instead, it must be interpreted ...
def parse_request_uri(self, uri):
if (uri == ASTERISK): return (None, None, uri) (scheme, sep, remainder) = uri.partition('://') if (sep and (QUESTION_MARK not in scheme)): (authority, path_a, path_b) = remainder.partition(FORWARD_SLASH) return (scheme.lower(), authority, (path_a + path_b)) if uri.startswith(FORW...
'takes quoted string and unquotes % encoded values'
def unquote_bytes(self, path):
res = path.split('%') for i in range(1, len(res)): item = res[i] try: res[i] = (bytes([int(item[:2], 16)]) + item[2:]) except ValueError: raise return ''.join(res)
'Call the gateway and write its iterable output.'
def respond(self):
mrbs = self.server.max_request_body_size if self.chunked_read: self.rfile = ChunkedRFile(self.conn.rfile, mrbs) else: cl = int(self.inheaders.get('Content-Length', 0)) if (mrbs and (mrbs < cl)): if (not self.sent_headers): self.simple_response('413 Requ...
'Write a simple response back to the client.'
def simple_response(self, status, msg=''):
status = str(status) buf = [(((bytes(self.server.protocol, 'ascii') + SPACE) + bytes(status, 'ISO-8859-1')) + CRLF), bytes(('Content-Length: %s\r\n' % len(msg)), 'ISO-8859-1'), 'Content-Type: text/plain\r\n'] if (status[:3] in ('413', '414')): self.close_connection = True if (self.resp...
'Write unbuffered data to the client.'
def write(self, chunk):
if (self.chunked_write and chunk): buf = [bytes(hex(len(chunk)), 'ASCII')[2:], CRLF, chunk, CRLF] self.conn.wfile.write(EMPTY.join(buf)) else: self.conn.wfile.write(chunk)
'Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this.'
def send_headers(self):
hkeys = [key.lower() for (key, value) in self.outheaders] status = int(self.status[:3]) if (status == 413): self.close_connection = True elif ('content-length' not in hkeys): if ((status < 200) or (status in (204, 205, 304))): pass elif ((self.response_protocol == 'HT...
'Read each request and respond appropriately.'
def communicate(self):
request_seen = False try: while True: req = None req = self.RequestHandlerClass(self.server, self) req.parse_request() if self.server.stats['Enabled']: self.requests_seen += 1 if (not req.ready): return ...
'Close the socket underlying this connection.'
def close(self):
self.rfile.close() if (not self.linger): self.socket.close() else: pass
'Start the pool of threads.'
def start(self):
for i in range(self.min): self._threads.append(WorkerThread(self.server)) for worker in self._threads: worker.setName(('CP Server ' + worker.getName())) worker.start() for worker in self._threads: while (not worker.ready): time.sleep(0.1)
'Number of worker threads which are idle. Read-only.'
def _get_idle(self):
return len([t for t in self._threads if (t.conn is None)])
'Spawn new worker threads (not above self.max).'
def grow(self, amount):
for i in range(amount): if ((self.max > 0) and (len(self._threads) >= self.max)): break worker = WorkerThread(self.server) worker.setName(('CP Server ' + worker.getName())) self._threads.append(worker) worker.start()
'Kill off worker threads (not below self.min).'
def shrink(self, amount):
for t in self._threads: if (not t.isAlive()): self._threads.remove(t) amount -= 1 if (amount > 0): for i in range(min(amount, (len(self._threads) - self.min))): self._queue.put(_SHUTDOWNREQUEST)
'Run the server forever.'
def start(self):
self._interrupt = None if (self.software is None): self.software = ('%s Server' % self.version) if isinstance(self.bind_addr, basestring): try: os.unlink(self.bind_addr) except: pass try: os.chmod(self.bind_addr, 511) except: ...
'Create (or recreate) the actual socket object.'
def bind(self, family, type, proto=0):
self.socket = socket.socket(family, type, proto) prevent_socket_inheritance(self.socket) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if (self.nodelay and (not isinstance(self.bind_addr, str))): self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if (self.s...
'Accept a new connection and put it on the Queue.'
def tick(self):
try: (s, addr) = self.socket.accept() if self.stats['Enabled']: self.stats['Accepts'] += 1 if (not self.ready): return prevent_socket_inheritance(s) if hasattr(s, 'settimeout'): s.settimeout(self.timeout) makefile = CP_makefile ...
'Gracefully shutdown a server that is serving forever.'
def stop(self):
self.ready = False if (self._start_time is not None): self._run_time += (time.time() - self._start_time) self._start_time = None sock = getattr(self, 'socket', None) if sock: if (not isinstance(self.bind_addr, basestring)): try: (host, port) = sock.getsock...
'Process the current request. Must be overridden in a subclass.'
def respond(self):
raise NotImplemented
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
raise NotImplemented
'Process the current request.'
def respond(self):
response = self.req.server.wsgi_app(self.env, self.start_response) try: for chunk in response: if chunk: if isinstance(chunk, unicodestr): chunk = chunk.encode('ISO-8859-1') self.write(chunk) finally: if hasattr(response, 'close...
'WSGI callable to begin the HTTP response.'
def start_response(self, status, headers, exc_info=None):
if (self.started_response and (not exc_info)): raise AssertionError('WSGI start_response called a second time with no exc_info.') self.started_response = True if self.req.sent_headers: try: raise exc_info[0](exc_info[1]).with_traceback(exc_info[2]) ...
'WSGI callable to write unbuffered data to the client. This method is also used internally by start_response (to write data from the iterable returned by the WSGI application).'
def write(self, chunk):
if (not self.started_response): raise AssertionError('WSGI write called before start_response.') chunklen = len(chunk) rbo = self.remaining_bytes_out if ((rbo is not None) and (chunklen > rbo)): if (not self.req.sent_headers): self.req.simple_response('500 Inte...
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
req = self.req env = {'ACTUAL_SERVER_PROTOCOL': req.server.protocol, 'PATH_INFO': req.path.decode('ISO-8859-1'), 'QUERY_STRING': req.qs.decode('ISO-8859-1'), 'REMOTE_ADDR': (req.conn.remote_addr or ''), 'REMOTE_PORT': str((req.conn.remote_port or '')), 'REQUEST_METHOD': req.method.decode('ISO-8859-1'), 'REQUEST...
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
req = self.req env_10 = WSGIGateway_10.get_environ(self) env = env_10.copy() env['wsgi.version'] = ('u', 0) env.setdefault('wsgi.url_encoding', 'utf-8') try: env['PATH_INFO'] = req.path.decode(env['wsgi.url_encoding']) env['QUERY_STRING'] = req.qs.decode(env['wsgi.url_encoding'])...
'Wrap and return the given socket.'
def bind(self, sock):
return sock
'Wrap and return the given socket, plus WSGI environ entries.'
def wrap(self, sock):
try: s = ssl.wrap_socket(sock, do_handshake_on_connect=True, server_side=True, certfile=self.certificate, keyfile=self.private_key, ssl_version=ssl.PROTOCOL_SSLv23) except ssl.SSLError: e = sys.exc_info()[1] if (e.errno == ssl.SSL_ERROR_EOF): return (None, {}) elif (e...
'Create WSGI environ entries to be merged into each request.'
def get_environ(self, sock):
cipher = sock.cipher() ssl_environ = {'wsgi.url_scheme': 'https', 'HTTPS': 'on', 'SSL_PROTOCOL': cipher[1], 'SSL_CIPHER': cipher[0]} return ssl_environ
'Wrap the given call with SSL error-trapping. is_reader: if False EOF errors will be raised. If True, EOF errors will return "" (to emulate normal sockets).'
def _safe_call(self, is_reader, call, *args, **kwargs):
start = time.time() while True: try: return call(*args, **kwargs) except SSL.WantReadError: time.sleep(self.ssl_retry) except SSL.WantWriteError: time.sleep(self.ssl_retry) except SSL.SysCallError as e: if (is_reader and (e.args == ...
'Wrap and return the given socket.'
def bind(self, sock):
if (self.context is None): self.context = self.get_context() conn = SSLConnection(self.context, sock) self._environ = self.get_environ() return conn
'Wrap and return the given socket, plus WSGI environ entries.'
def wrap(self, sock):
return (sock, self._environ.copy())
'Return an SSL.Context from self attributes.'
def get_context(self):
c = SSL.Context(SSL.SSLv23_METHOD) c.use_privatekey_file(self.private_key) if self.certificate_chain: c.load_verify_locations(self.certificate_chain) c.use_certificate_file(self.certificate) return c
'Return WSGI environ entries to be merged into each request.'
def get_environ(self):
ssl_environ = {'HTTPS': 'on'} if self.certificate: cert = open(self.certificate, 'rb').read() cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert) ssl_environ.update({'SSL_SERVER_M_VERSION': cert.get_version(), 'SSL_SERVER_M_SERIAL': cert.get_serial_number()}) for (prefix, d...
'Parse the next HTTP request start-line and message-headers.'
def parse_request(self):
self.rfile = SizeCheckWrapper(self.conn.rfile, self.server.max_request_header_size) try: success = self.read_request_line() except MaxSizeExceeded: self.simple_response('414 Request-URI Too Long', 'The Request-URI sent with the request exceeds the maximum ...
'Read self.rfile into self.inheaders. Return success.'
def read_request_headers(self):
try: read_headers(self.rfile, self.inheaders) except ValueError: ex = sys.exc_info()[1] self.simple_response('400 Bad Request', ex.args[0]) return False mrbs = self.server.max_request_body_size if (mrbs and (int(self.inheaders.get('Content-Length', 0)) > mrbs)): ...
'Parse a Request-URI into (scheme, authority, path). Note that Request-URI\'s must be one of:: Request-URI = "*" | absoluteURI | abs_path | authority Therefore, a Request-URI which starts with a double forward-slash cannot be a "net_path":: net_path = "//" authority [ abs_path ] Instead, it must be interpreted ...
def parse_request_uri(self, uri):
if (uri == ASTERISK): return (None, None, uri) i = uri.find('://') if ((i > 0) and (QUESTION_MARK not in uri[:i])): (scheme, remainder) = (uri[:i].lower(), uri[(i + 3):]) (authority, path) = remainder.split(FORWARD_SLASH, 1) path = (FORWARD_SLASH + path) return (schem...
'Call the gateway and write its iterable output.'
def respond(self):
mrbs = self.server.max_request_body_size if self.chunked_read: self.rfile = ChunkedRFile(self.conn.rfile, mrbs) else: cl = int(self.inheaders.get('Content-Length', 0)) if (mrbs and (mrbs < cl)): if (not self.sent_headers): self.simple_response('413 Requ...
'Write a simple response back to the client.'
def simple_response(self, status, msg=''):
status = str(status) buf = [(((self.server.protocol + SPACE) + status) + CRLF), ('Content-Length: %s\r\n' % len(msg)), 'Content-Type: text/plain\r\n'] if (status[:3] in ('413', '414')): self.close_connection = True if (self.response_protocol == 'HTTP/1.1'): buf.append('Conn...
'Write unbuffered data to the client.'
def write(self, chunk):
if (self.chunked_write and chunk): buf = [hex(len(chunk))[2:], CRLF, chunk, CRLF] self.conn.wfile.sendall(EMPTY.join(buf)) else: self.conn.wfile.sendall(chunk)
'Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this.'
def send_headers(self):
hkeys = [key.lower() for (key, value) in self.outheaders] status = int(self.status[:3]) if (status == 413): self.close_connection = True elif ('content-length' not in hkeys): if ((status < 200) or (status in (204, 205, 304))): pass elif ((self.response_protocol == 'HT...
'Sendall for non-blocking sockets.'
def sendall(self, data):
while data: try: bytes_sent = self.send(data) data = data[bytes_sent:] except socket.error as e: if (e.args[0] not in socket_errors_nonblocking): raise
'Read each request and respond appropriately.'
def communicate(self):
request_seen = False try: while True: req = None req = self.RequestHandlerClass(self.server, self) req.parse_request() if self.server.stats['Enabled']: self.requests_seen += 1 if (not req.ready): return ...
'Close the socket underlying this connection.'
def close(self):
self.rfile.close() if (not self.linger): if hasattr(self.socket, '_sock'): self.socket._sock.close() self.socket.close() else: pass
'Start the pool of threads.'
def start(self):
for i in range(self.min): self._threads.append(WorkerThread(self.server)) for worker in self._threads: worker.setName(('CP Server ' + worker.getName())) worker.start() for worker in self._threads: while (not worker.ready): time.sleep(0.1)
'Number of worker threads which are idle. Read-only.'
def _get_idle(self):
return len([t for t in self._threads if (t.conn is None)])
'Spawn new worker threads (not above self.max).'
def grow(self, amount):
for i in range(amount): if ((self.max > 0) and (len(self._threads) >= self.max)): break worker = WorkerThread(self.server) worker.setName(('CP Server ' + worker.getName())) self._threads.append(worker) worker.start()
'Kill off worker threads (not below self.min).'
def shrink(self, amount):
for t in self._threads: if (not t.isAlive()): self._threads.remove(t) amount -= 1 if (amount > 0): for i in range(min(amount, (len(self._threads) - self.min))): self._queue.put(_SHUTDOWNREQUEST)
'Run the server forever.'
def start(self):
self._interrupt = None if (self.software is None): self.software = ('%s Server' % self.version) if ((self.ssl_adapter is None) and getattr(self, 'ssl_certificate', None) and getattr(self, 'ssl_private_key', None)): warnings.warn('SSL attributes are deprecated in CherryPy ...
'Create (or recreate) the actual socket object.'
def bind(self, family, type, proto=0):
self.socket = socket.socket(family, type, proto) prevent_socket_inheritance(self.socket) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if (self.nodelay and (not isinstance(self.bind_addr, str))): self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if (self.s...
'Accept a new connection and put it on the Queue.'
def tick(self):
try: (s, addr) = self.socket.accept() if self.stats['Enabled']: self.stats['Accepts'] += 1 if (not self.ready): return prevent_socket_inheritance(s) if hasattr(s, 'settimeout'): s.settimeout(self.timeout) makefile = CP_fileobject ...
'Gracefully shutdown a server that is serving forever.'
def stop(self):
self.ready = False if (self._start_time is not None): self._run_time += (time.time() - self._start_time) self._start_time = None sock = getattr(self, 'socket', None) if sock: if (not isinstance(self.bind_addr, basestring)): try: (host, port) = sock.getsock...
'Process the current request. Must be overridden in a subclass.'
def respond(self):
raise NotImplemented
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
raise NotImplemented
'Process the current request.'
def respond(self):
response = self.req.server.wsgi_app(self.env, self.start_response) try: for chunk in response: if chunk: if isinstance(chunk, unicodestr): chunk = chunk.encode('ISO-8859-1') self.write(chunk) finally: if hasattr(response, 'close...
'WSGI callable to begin the HTTP response.'
def start_response(self, status, headers, exc_info=None):
if (self.started_response and (not exc_info)): raise AssertionError('WSGI start_response called a second time with no exc_info.') self.started_response = True if self.req.sent_headers: try: raise exc_info[0], exc_info[1], exc_info[2] finally: ...
'WSGI callable to write unbuffered data to the client. This method is also used internally by start_response (to write data from the iterable returned by the WSGI application).'
def write(self, chunk):
if (not self.started_response): raise AssertionError('WSGI write called before start_response.') chunklen = len(chunk) rbo = self.remaining_bytes_out if ((rbo is not None) and (chunklen > rbo)): if (not self.req.sent_headers): self.req.simple_response('500 Inte...
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
req = self.req env = {'ACTUAL_SERVER_PROTOCOL': req.server.protocol, 'PATH_INFO': req.path, 'QUERY_STRING': req.qs, 'REMOTE_ADDR': (req.conn.remote_addr or ''), 'REMOTE_PORT': str((req.conn.remote_port or '')), 'REQUEST_METHOD': req.method, 'REQUEST_URI': req.uri, 'SCRIPT_NAME': '', 'SERVER_NAME': req.server.se...
'Return a new environ dict targeting the given wsgi.version'
def get_environ(self):
req = self.req env_10 = WSGIGateway_10.get_environ(self) env = dict([(k.decode('ISO-8859-1'), v) for (k, v) in env_10.iteritems()]) env[u'wsgi.version'] = ('u', 0) env.setdefault(u'wsgi.url_encoding', u'utf-8') try: for key in [u'PATH_INFO', u'SCRIPT_NAME', u'QUERY_STRING']: ...
'Close and de-reference the current request and response. (Core)'
def close(self):
self.cpapp.release_serving()
'Create a Request object using environ.'
def run(self):
env = self.environ.get local = httputil.Host('', int(env('SERVER_PORT', 80)), env('SERVER_NAME', '')) remote = httputil.Host(env('REMOTE_ADDR', ''), int((env('REMOTE_PORT', (-1)) or (-1))), env('REMOTE_HOST', '')) scheme = env('wsgi.url_scheme') sproto = env('ACTUAL_SERVER_PROTOCOL', 'HTTP/1.1') ...
'Translate CGI-environ header names to HTTP header names.'
def translate_headers(self, environ):
for cgiName in environ: if (cgiName in self.headerNames): (yield (self.headerNames[cgiName], environ[cgiName])) elif (cgiName[:5] == 'HTTP_'): translatedHeader = cgiName[5:].replace('_', '-') (yield (translatedHeader, environ[cgiName]))
'WSGI application callable for the actual CherryPy application. You probably shouldn\'t call this; call self.__call__ instead, so that any WSGI middleware in self.pipeline can run first.'
def tail(self, environ, start_response):
return self.response_class(environ, start_response, self.cpapp)
'Config handler for the \'wsgi\' namespace.'
def namespace_handler(self, k, v):
if (k == 'pipeline'): self.pipeline.extend(v) elif (k == 'response_class'): self.response_class = v else: (name, arg) = k.split('.', 1) bucket = self.config.setdefault(name, {}) bucket[arg] = v
'Constructor. Args: request: Request associated with this RPC.'
def __init__(self, request):
self.__request = request self.__response = None self.__state = remote.RpcState.RUNNING self.__error_message = None self.__error_name = None
'Request associated with RPC.'
@property def request(self):
return self.__request
'Response associated with RPC.'
@property def response(self):
self.wait() self.__check_status() return self.__response
'State associated with RPC.'
@property def state(self):
return self.__state
'Error, if any, associated with RPC.'
@property def error_message(self):
self.wait() return self.__error_message
'Error name, if any, associated with RPC.'
@property def error_name(self):
self.wait() return self.__error_name
'Wait for an RPC to finish.'
def wait(self):
if (self.__state == remote.RpcState.RUNNING): self._wait_impl()
'Implementation for wait().'
def _wait_impl(self):
raise NotImplementedError()
'Constructor. Args: protocol: If string, will look up a protocol from the default Protocols instance by name. Can also be an instance of remote.ProtocolConfig. If neither, it must be an object that implements a protocol interface by implementing encode_message, decode_message and set CONTENT_TYPE. For example, the mod...
@util.positional(1) def __init__(self, protocol=protobuf):
if isinstance(protocol, basestring): protocols = remote.Protocols.get_default() try: protocol = protocols.lookup_by_name(protocol) except KeyError: protocol = protocols.lookup_by_content_type(protocol) if isinstance(protocol, remote.ProtocolConfig): self._...
'Protocol associated with this transport.'
@property def protocol(self):
return self.__protocol
'Protocol associated with this transport.'
@property def protocol_config(self):
return self.__protocol_config
'Initiate sending an RPC over the transport. Args: remote_info: RemoteInfo instance describing remote method. request: Request message to send to service. Returns: An Rpc instance intialized with the request..'
def send_rpc(self, remote_info, request):
request.check_initialized() rpc = self._start_rpc(remote_info, request) return rpc
'Start a remote procedure call. Args: remote_info: RemoteInfo instance describing remote method. request: Request message to send to service. Returns: An Rpc instance initialized with the request.'
def _start_rpc(self, remote_info, request):
raise NotImplementedError()
'Constructor. Args: service_url: URL where the service is located. All communication via the transport will go to this URL. protocol: The protocol implementation. Must implement encode_message and decode_message. Can also be an instance of remote.ProtocolConfig.'
@util.positional(2) def __init__(self, service_url, protocol=protobuf, connection_class=httplib.HTTPConnection):
super(HttpTransport, self).__init__(protocol=protocol) self.__service_url = service_url self.__connection_class = connection_class
'Get RPC status from HTTP response. Args: response: HTTPResponse object. content: Content read from HTTP response. Returns: RpcStatus object parsed from response, else an RpcStatus with a generic HTTP error.'
def __get_rpc_status(self, response, content):
if (response.status >= 400): content_type = response.getheader('content-type') if (content_type == self.protocol_config.default_content_type): try: rpc_status = self.protocol.decode_message(remote.RpcStatus, content) except Exception as decode_err: ...
'Set response on RPC. Sets response or status from HTTP request. Implements the wait method of Rpc instance. Args: remote_info: Remote info for invoked RPC. connection: HTTPConnection that is making request. rpc: Rpc instance.'
def __set_response(self, remote_info, connection, rpc):
try: response = connection.getresponse() content = response.read() if (response.status == httplib.OK): response = self.protocol.decode_message(remote_info.response_type, content) rpc.set_response(response) else: status = self.__get_rpc_status(respo...
'Start a remote procedure call. Args: remote_info: A RemoteInfo instance for this RPC. request: The request message for this RPC. Returns: An Rpc instance initialized with a Request.'
def _start_rpc(self, remote_info, request):
method_url = ('%s.%s' % (self.__service_url, remote_info.method.func_name)) encoded_request = self.protocol.encode_message(request) url = urlparse.urlparse(method_url) if (url.scheme == 'https'): connection_type = httplib.HTTPSConnection else: connection_type = httplib.HTTPConnection...
'Constructor. Args: service_factory: Service factory or class.'
def __init__(self, service_factory):
super(LocalTransport, self).__init__() self.__service_class = getattr(service_factory, 'service_class', service_factory) self.__service_factory = service_factory
'Start a remote procedure call. Args: remote_info: RemoteInfo instance describing remote method. request: Request message to send to service. Returns: An Rpc instance initialized with the request.'
def _start_rpc(self, remote_info, request):
rpc = Rpc(request) def wait_impl(): instance = self.__service_factory() try: initalize_request_state = instance.initialize_request_state except AttributeError: pass else: host = unicode(os.uname()[1]) initalize_request_state(remote....
'Parse component of an Accept header. Args: accept_header: Unparsed sub-expression of accept header. index: The index that this accept item was found in the Accept header.'
def __init__(self, accept_header, index):
accept_header = accept_header.lower() (content_type, values) = cgi.parse_header(accept_header) match = self.__CONTENT_TYPE_REGEX.match(content_type) if (not match): raise AcceptError(('Not valid Accept header: %s' % accept_header)) self.__index = index self.__main_type = matc...
'Copy the dictionary of values parsed from the header fragment.'
@property def values(self):
return dict(self.__values)
'Determine if the given accept header matches content type. Args: content_type: Unparsed content type string. Returns: True if accept header matches content type, else False.'
def match(self, content_type):
(content_type, _) = cgi.parse_header(content_type) match = self.__CONTENT_TYPE_REGEX.match(content_type.lower()) if (not match): return False (main_type, sub_type) = (match.group(1), match.group(2)) if (not (main_type and sub_type)): return False return (((self.__main_type is Non...
'Comparison operator based on sort keys.'
def __cmp__(self, other):
if (not isinstance(other, AcceptItem)): return NotImplemented return cmp(self.sort_key, other.sort_key)
'Rebuilds Accept header.'
def __str__(self):
content_type = ('%s/%s' % ((self.__main_type or '*'), (self.__sub_type or '*'))) values = self.values if values: value_strings = [('%s=%s' % (i, v)) for (i, v) in values.iteritems()] return ('%s; %s' % (content_type, '; '.join(value_strings))) else: return content_type
'Initialize a time zone offset. Args: offset: Integer or timedelta time zone offset, in minutes from UTC. This can be negative.'
def __init__(self, offset):
super(TimeZoneOffset, self).__init__() if isinstance(offset, datetime.timedelta): offset = offset.total_seconds() self.__offset = offset
'Get the a timedelta with the time zone\'s offset from UTC. Returns: The time zone offset from UTC, as a timedelta.'
def utcoffset(self, dt):
return datetime.timedelta(minutes=self.__offset)
'Get the daylight savings time offset. The formats that ProtoRPC uses to encode/decode time zone information don\'t contain any information about daylight savings time. So this always returns a timedelta of 0. Returns: A timedelta of 0.'
def dst(self, dt):
return datetime.timedelta(0)
'Constructor. Args: descriptors: A dictionary or dictionary-like object that can be used to store and cache descriptors by definition name. definition_loader: A function used for resolving missing descriptors. The function takes a definition name as its parameter and returns an appropriate descriptor. It may raise Def...
@util.positional(1) def __init__(self, descriptors=None, descriptor_loader=import_descriptor_loader):
self.__descriptor_loader = descriptor_loader self.__descriptors = (descriptors or {})
'Lookup descriptor by name. Get descriptor from library by name. If descriptor is not found will attempt to find via descriptor loader if provided. Args: definition_name: Definition name to find. Returns: Descriptor that describes definition name. Raises: DefinitionNotFoundError if not descriptor exists for definition...
def lookup_descriptor(self, definition_name):
try: return self.__descriptors[definition_name] except KeyError: pass if self.__descriptor_loader: definition = self.__descriptor_loader(definition_name) self.__descriptors[definition_name] = definition return definition else: raise messages.DefinitionNotF...
'Determines the package name for any definition. Determine the package that any definition name belongs to. May check parent for package name and will resolve missing descriptors if provided descriptor loader. Args: definition_name: Definition name to find package for.'
def lookup_package(self, definition_name):
while True: descriptor = self.lookup_descriptor(definition_name) if isinstance(descriptor, FileDescriptor): return descriptor.package else: index = definition_name.rfind('.') if (index < 0): return None definition_name = definit...
'Get error class from RpcState. Args: state: RpcState value. Can be enum value itself, string or int. Returns: Exception class mapped to value if state is an error. Returns None if state is OK or RUNNING.'
@classmethod def from_state(cls, state):
return _RPC_STATE_TO_ERROR.get(RpcState(state))
'Constructor. Args: message: Application specific error message. error_name: Application specific error name. Must be None, string or unicode string.'
def __init__(self, message, error_name=None):
super(ApplicationError, self).__init__(message) self.error_name = error_name
'Constructor. Args: method: The method which implements the remote method. This is a function that will act as an instance method of a class definition that is decorated by \'@method\'. It must always take \'self\' as its first parameter. request_type: Expected request type for the remote method. response_type: Expec...
def __init__(self, method, request_type, response_type):
self.__method = method self.__request_type = request_type self.__response_type = response_type