desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Consumes a string value. Returns: The string parsed. Raises: ParseError: If a string value couldn\'t be consumed.'
def ConsumeString(self):
the_bytes = self.ConsumeByteString() try: return unicode(the_bytes, 'utf-8') except UnicodeDecodeError as e: raise self._StringParseError(e)
'Consumes a byte array value. Returns: The array parsed (as a string). Raises: ParseError: If a byte array value couldn\'t be consumed.'
def ConsumeByteString(self):
the_list = [self._ConsumeSingleByteString()] while (self.token and (self.token[0] in ("'", '"'))): the_list.append(self._ConsumeSingleByteString()) return ''.join(the_list)
'Consume one token of a string literal. String literals (whether bytes or text) can come in multiple adjacent tokens which are automatically concatenated, like in C or Python. This method only consumes one token.'
def _ConsumeSingleByteString(self):
text = self.token if ((len(text) < 1) or (text[0] not in ("'", '"'))): raise self._ParseError('Expected string.') if ((len(text) < 2) or (text[(-1)] != text[0])): raise self._ParseError('String missing ending quote.') try: result = _CUnescape(text[1:(-1)]) except ...
'Creates and *returns* a ParseError for the previously read token. Args: message: A message to set for the exception. Returns: A ParseError instance.'
def ParseErrorPreviousToken(self, message):
return ParseError(('%d:%d : %s' % ((self._previous_line + 1), (self._previous_column + 1), message)))
'Creates and *returns* a ParseError for the current token.'
def _ParseError(self, message):
return ParseError(('%d:%d : %s' % ((self._line + 1), (self._column + 1), message)))
'Reads the next meaningful token.'
def NextToken(self):
self._previous_line = self._line self._previous_column = self._column self._column += len(self.token) self._SkipWhitespace() if ((not self._lines) and (len(self._current_line) <= self._column)): self.token = '' return match = self._TOKEN.match(self._current_line, self._column) ...
'Type check the provided value and return it. The returned value might have been normalized to another type.'
def CheckValue(self, proposed_value):
if (not isinstance(proposed_value, self._acceptable_types)): message = ('%.1024r has type %s, but expected one of: %s' % (proposed_value, type(proposed_value), self._acceptable_types)) raise TypeError(message) return proposed_value
'Args: message_listener: A MessageListener implementation. The RepeatedScalarFieldContainer will call this object\'s Modified() method when it is modified.'
def __init__(self, message_listener):
self._message_listener = message_listener self._values = []
'Retrieves item by the specified key.'
def __getitem__(self, key):
return self._values[key]
'Returns the number of elements in the container.'
def __len__(self):
return len(self._values)
'Checks if another instance isn\'t equal to this one.'
def __ne__(self, other):
return (not (self == other))
'Args: message_listener: A MessageListener implementation. The RepeatedScalarFieldContainer will call this object\'s Modified() method when it is modified. type_checker: A type_checkers.ValueChecker instance to run on elements inserted into this container.'
def __init__(self, message_listener, type_checker):
super(RepeatedScalarFieldContainer, self).__init__(message_listener) self._type_checker = type_checker
'Appends an item to the list. Similar to list.append().'
def append(self, value):
self._values.append(self._type_checker.CheckValue(value)) if (not self._message_listener.dirty): self._message_listener.Modified()
'Inserts the item at the specified position. Similar to list.insert().'
def insert(self, key, value):
self._values.insert(key, self._type_checker.CheckValue(value)) if (not self._message_listener.dirty): self._message_listener.Modified()
'Extends by appending the given sequence. Similar to list.extend().'
def extend(self, elem_seq):
if (not elem_seq): return new_values = [] for elem in elem_seq: new_values.append(self._type_checker.CheckValue(elem)) self._values.extend(new_values) self._message_listener.Modified()
'Appends the contents of another repeated field of the same type to this one. We do not check the types of the individual fields.'
def MergeFrom(self, other):
self._values.extend(other._values) self._message_listener.Modified()
'Removes an item from the list. Similar to list.remove().'
def remove(self, elem):
self._values.remove(elem) self._message_listener.Modified()
'Sets the item on the specified position.'
def __setitem__(self, key, value):
self._values[key] = self._type_checker.CheckValue(value) self._message_listener.Modified()
'Retrieves the subset of items from between the specified indices.'
def __getslice__(self, start, stop):
return self._values[start:stop]
'Sets the subset of items from between the specified indices.'
def __setslice__(self, start, stop, values):
new_values = [] for value in values: new_values.append(self._type_checker.CheckValue(value)) self._values[start:stop] = new_values self._message_listener.Modified()
'Deletes the item at the specified position.'
def __delitem__(self, key):
del self._values[key] self._message_listener.Modified()
'Deletes the subset of items from between the specified indices.'
def __delslice__(self, start, stop):
del self._values[start:stop] self._message_listener.Modified()
'Compares the current instance with another one.'
def __eq__(self, other):
if (self is other): return True if isinstance(other, self.__class__): return (other._values == self._values) return (other == self._values)
'Note that we pass in a descriptor instead of the generated directly, since at the time we construct a _RepeatedCompositeFieldContainer we haven\'t yet necessarily initialized the type that will be contained in the container. Args: message_listener: A MessageListener implementation. The RepeatedCompositeFieldContainer ...
def __init__(self, message_listener, message_descriptor):
super(RepeatedCompositeFieldContainer, self).__init__(message_listener) self._message_descriptor = message_descriptor
'Adds a new element at the end of the list and returns it. Keyword arguments may be used to initialize the element.'
def add(self, **kwargs):
new_element = self._message_descriptor._concrete_class(**kwargs) new_element._SetListener(self._message_listener) self._values.append(new_element) if (not self._message_listener.dirty): self._message_listener.Modified() return new_element
'Extends by appending the given sequence of elements of the same type as this one, copying each individual message.'
def extend(self, elem_seq):
message_class = self._message_descriptor._concrete_class listener = self._message_listener values = self._values for message in elem_seq: new_element = message_class() new_element._SetListener(listener) new_element.MergeFrom(message) values.append(new_element) listene...
'Appends the contents of another repeated field of the same type to this one, copying each individual message.'
def MergeFrom(self, other):
self.extend(other._values)
'Removes an item from the list. Similar to list.remove().'
def remove(self, elem):
self._values.remove(elem) self._message_listener.Modified()
'Retrieves the subset of items from between the specified indices.'
def __getslice__(self, start, stop):
return self._values[start:stop]
'Deletes the item at the specified position.'
def __delitem__(self, key):
del self._values[key] self._message_listener.Modified()
'Deletes the subset of items from between the specified indices.'
def __delslice__(self, start, stop):
del self._values[start:stop] self._message_listener.Modified()
'Compares the current instance with another one.'
def __eq__(self, other):
if (self is other): return True if (not isinstance(other, self.__class__)): raise TypeError('Can only compare repeated composite fields against other repeated composite fields.') return (self._values == other._values)
'Args: parent_message: The message whose _Modified() method we should call when we receive Modified() messages.'
def __init__(self, parent_message):
if isinstance(parent_message, weakref.ProxyType): self._parent_message_weakref = parent_message else: self._parent_message_weakref = weakref.proxy(parent_message) self.dirty = False
'extended_message: Message instance for which we are the Extensions dict.'
def __init__(self, extended_message):
self._extended_message = extended_message
'Returns the current value of the given extension handle.'
def __getitem__(self, extension_handle):
_VerifyExtensionHandle(self._extended_message, extension_handle) result = self._extended_message._fields.get(extension_handle) if (result is not None): return result if (extension_handle.label == _FieldDescriptor.LABEL_REPEATED): result = extension_handle._default_constructor(self._exten...
'If extension_handle specifies a non-repeated, scalar extension field, sets the value of that field.'
def __setitem__(self, extension_handle, value):
_VerifyExtensionHandle(self._extended_message, extension_handle) if ((extension_handle.label == _FieldDescriptor.LABEL_REPEATED) or (extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE)): raise TypeError(('Cannot assign to extension "%s" because it is a repeated o...
'Tries to find a known extension with the specified name. Args: name: Extension full name. Returns: Extension field descriptor.'
def _FindExtensionByName(self, name):
return self._extended_message._extensions_by_name.get(name, None)
'Called every time the message is modified in such a way that the parent message may need to be updated. This currently means either: (a) The message was modified for the first time, so the parent message should henceforth mark the message as present. (b) The message\'s cached byte size became dirty -- i.e. the messag...
def Modified(self):
raise NotImplementedError
'Inits EnumTypeWrapper with an EnumDescriptor.'
def __init__(self, enum_type):
self._enum_type = enum_type self.DESCRIPTOR = enum_type
'Returns a string containing the name of an enum value.'
def Name(self, number):
if (number in self._enum_type.values_by_number): return self._enum_type.values_by_number[number].name raise ValueError(('Enum %s has no name defined for value %d' % (self._enum_type.name, number)))
'Returns the value coresponding to the given enum name.'
def Value(self, name):
if (name in self._enum_type.values_by_name): return self._enum_type.values_by_name[name].number raise ValueError(('Enum %s has no value defined for name %s' % (self._enum_type.name, name)))
'Return a list of the string names in the enum. These are returned in the order they were defined in the .proto file.'
def keys(self):
return [value_descriptor.name for value_descriptor in self._enum_type.values]
'Return a list of the integer values in the enum. These are returned in the order they were defined in the .proto file.'
def values(self):
return [value_descriptor.number for value_descriptor in self._enum_type.values]
'Return a list of the (name, value) pairs of the enum. These are returned in the order they were defined in the .proto file.'
def items(self):
return [(value_descriptor.name, value_descriptor.number) for value_descriptor in self._enum_type.values]
'Creates an object representing a child process. Only one of the given args should be provided (except for instance_id when backend_id is specified). Args: app_instance: (int) The process represents the indicated app instance. backend_id: (string) The process represents a backend. instance_id: (int) The process represe...
def __init__(self, host, port, app_instance=None, backend_id=None, instance_id=None, frontend_port=None):
self.app_instance = app_instance self.backend_id = backend_id self.instance_id = instance_id self.process = None self.argv = [] self.started = False self.connection_handler = httplib.HTTPConnection self.SetHostPort(host, port) self.frontend_port = frontend_port
'Sets the host and port that this process listens on.'
def SetHostPort(self, host, port):
self.host = host self.port = port if self.backend_id: backends_api._set_dev_port(self.port, self.backend_id, self.instance_id)
'Returns the URL for this process.'
def Address(self):
return ('http://%s:%d' % self.HostPort())
'Returns the address of this process as a (host, port) pair.'
def HostPort(self):
return (self.host, self.port)
'Starts the child process. Args: argv: The argv of the parent process. When starting the subprocess, we make a copy of the parent\'s argv, then modify it in accordance with how the ChildProcess is configured, to represent different processes in the multiprocess dev_appserver. api_port: The port on which the API Server ...
def Start(self, argv, api_port):
self.argv = copy.deepcopy(argv) self.api_port = api_port self.SetFlag('--multiprocess') self.SetFlag('--address', short_flag='-a', value=self.host) self.SetFlag('--port', short_flag='-p', value=self.port) self.SetFlag('--multiprocess_api_port', value=self.api_port) if (self.frontend_port is ...
'Starts a thread to periodically send /_ah/start to this instance. We need a thread to do this because we want to restart any resident Backends that have been shutdown, and because a backend instance is not considered to be ready for serving until it has successfully responded to /_ah/start.'
def EnableStartRequests(self):
if (self.backend_id and (self.instance_id is not None)): self.start_thread = StartInstance(self) self.start_thread.start()
'Attempts to connect to the child process. Returns: bool: Whether a connection was made.'
def Connect(self):
logging.debug('Attempting connection to %s', self) sock = None result = True try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(self.HostPort()) except: result = False if sock: sock.close() return result
'Blocks until the child process has started. This method repeatedly attempts to connect to the process on its HTTP server port. Returns when a connection has been successfully established or the timeout has been reached. Args: timeout_s: Amount of time to wait, in seconds. poll_period_s: Time to wait between connectio...
def WaitForConnection(self, timeout_s=30.0, poll_period_s=0.5):
finish_time = (time.time() + timeout_s) while (time.time() < finish_time): if self.Connect(): return True time.sleep(poll_period_s) logging.info('%s took more than %d seconds to start.', self, timeout_s) return False
'If the process has not been started, sends a request to /_ah/start.'
def SendStartRequest(self):
if self.started: return try: response = self.SendRequest('GET', '/_ah/start') rc = response.status if (((rc >= 200) and (rc < 300)) or (rc == 404)): self.started = True except KeyboardInterrupt: pass except Exception as e: logging.error('Failed...
'Sends an HTTP request to this process. Args: command: The HTTP command (e.g., GET, POST) path: The URL path for the request. headers: A dictionary containing headers as key-value pairs.'
def SendRequest(self, command, path, payload=None, headers=None):
logging.debug(('send request: %s %s to %s' % (command, path, self))) connection = self.connection_handler(('%s:%d' % self.HostPort())) connection.request(command, path, payload, (headers or {})) response = connection.getresponse() return response
'Add a flag to self.argv, replacing the existing value if set. Args: flag: flag to remove. short_flag: one letter short version of the flag (optional) value: Value of the flag (optional)'
def SetFlag(self, flag, short_flag=None, value=None):
self.RemoveFlag(flag, short_flag=short_flag, has_value=(value is not None)) if (value is None): self.argv.append(flag) else: self.argv.append(((flag + '=') + str(value)))
'Removes an argument from self.argv. Args: flag: flag to remove. short_flag: one letter short version of the flag has_value: True if the next argument after the short flag is the value.'
def RemoveFlag(self, flag, short_flag=None, has_value=False):
new_argv = [] index = 0 while (index < len(self.argv)): value = self.argv[index] index += 1 if (flag == value): if has_value: index += 1 continue if (has_value and value.startswith((flag + '='))): continue if (short_...
'Creates a DevProcess with a default configuration.'
def __init__(self):
self.process_type = None self.desc = None self.http_server = None self.app_id = None self.backends = None self.app_instance = None self.backend_id = None self.instance_id = None self.backend_entry = None self.host = None self.port = None self.api_port = None self.mult...
'Supplies a list of backends for future use. Args: appinfo: An AppInfoExternal object. backends: List of BackendEntry objects. options: Dictionary of command-line options.'
def Init(self, appinfo, backends, options):
self.backends = backends self.options = options self.app_id = appinfo.application self.host = options[ARG_ADDRESS] self.port = options[ARG_PORT] if (ARG_MULTIPROCESS_APP_INSTANCE_ID in options): self.SetType(DevProcess.TYPE_APP_INSTANCE) self.app_instance = options[ARG_MULTIPROCE...
'Finds the entry for the backend this process represents, if any.'
def InitBackendEntry(self):
for backend in self.backends: if (backend.name == self.backend_id): self.backend_entry = backend if (not self.backend_entry): raise Error(('No backend entry found for: ' % self))
'Returns the HTTPServer used by this process.'
def HttpServer(self):
return self.http_server
'Returns the address of this process.'
def Address(self):
return ('http://%s:%d' % (self.host, self.port))
'Sets the http_server to be used when handling requests. Args: http_server: An HTTPServer that receives requests.'
def SetHttpServer(self, http_server):
self.http_server = http_server self.handle_requests = HandleRequestThread() self.handle_requests.start()
'Starts the set of child processes.'
def StartChildren(self, argv, options):
self.children = [] base_port = self.multiprocess_min_port self.frontend_port = base_port next_port = base_port self.child_app_instance = ChildProcess(self.host, next_port, app_instance=0) self.children.append(self.child_app_instance) next_port += 1 for backend in self.backends: b...
'Acquires a random port for each child process.'
def AssignPortsRandomly(self):
bound = [] for child in self.children: sock = socket.socket() sock.bind(('localhost', 0)) bound.append(sock) child.SetHostPort(self.host, sock.getsockname()[1]) for sock in bound: sock.close()
'Indicates whether this is the default dev_appserver process.'
def IsDefault(self):
return (self.Type() is None)
'Indicates whether this is the master process.'
def IsMaster(self):
return (self.Type() == DevProcess.TYPE_MASTER)
'Indicates that this is a subprocessess of the dev_appserver.'
def IsSubprocess(self):
return (not (self.IsDefault() or self.IsMaster()))
'Indicates whether this process represents an application instance.'
def IsAppInstance(self):
return (self.Type() == DevProcess.TYPE_APP_INSTANCE)
'Indicates whether this process represents a backend.'
def IsBackend(self):
return (self.IsBackendBalancer() or self.IsBackendInstance())
'Indicates whether this process represents a backend load balancer.'
def IsBackendBalancer(self):
return (self.Type() == DevProcess.TYPE_BACKEND_BALANCER)
'Indicates whether this process represents a backend instance.'
def IsBackendInstance(self):
return (self.Type() == DevProcess.TYPE_BACKEND_INSTANCE)
'Indicates whether this process represents a load balancer.'
def IsBalancer(self):
return (self.IsMaster() or self.IsBackendBalancer())
'Indicates whether this process represents an instance.'
def IsInstance(self):
return (self.IsAppInstance() or self.IsBackendInstance())
'Construct a list of instances to balance traffic over.'
def InitBalanceSet(self):
if self.IsMaster(): self.balance_set = [self.child_app_instance.port] if self.IsBackendBalancer(): self.balance_set = [] for instance in xrange(self.backend_entry.instances): port = backends_api._get_dev_port(self.backend_id, instance) self.balance_set.append(port...
'Return the set of ports over which this process balances requests.'
def GetBalanceSet(self):
return self.balance_set
'Indicates whether this process has fail-fast behavior.'
def FailFast(self):
if (not self.backend_entry): return False if self.backend_entry.failfast: return True return False
'Print the start message for processes that are started automatically.'
def PrintStartMessage(self, app_id, host, port):
url = ('http://%s:%d' % (host, port)) admin_url = ('%s/_ah/admin' % url) if (not self.IsSubprocess()): logging.info('Running application %s on port %d: %s', app_id, port, url) logging.info('Admin console is available at: %s', admin_url)
'Returns the children of this process.'
def Children(self):
return self.children
'Set up stubs using remote_api as appropriate. If this is the API server (or is not multiprocess), return False. Otherwise, set up the stubs for data based APIs as remote stubs pointing at the to the API server and return True.'
def MaybeConfigureRemoteDataApis(self):
if self.IsDefault(): return False services = ('app_identity_service', 'capability_service', 'datastore_v3', 'mail', 'memcache', 'taskqueue', 'urlfetch', 'xmpp') remote_api_stub.ConfigureRemoteApi(self.app_id, PATH_DEV_API_SERVER, (lambda : ('', '')), servername=('%s:%d' % (API_SERVER_HOST, self.api_...
'Called when a new appinfo is read from disk on each request. The only action we take is to apply backend settings, such as the \'start\' directive, which adds a handler for /_ah/start. Args: appinfo: An AppInfoExternal to be used on the next request.'
def NewAppInfo(self, appinfo):
if self.backends: appinfo.backends = self.backends if self.IsBackend(): appinfo.ApplyBackendSettings(self.backend_id)
'Copies backend port information to the supplied environment dictionary. This information is used by the Backends API to resolve backend and instance addresses in the dev_appserver. User-supplied code has no access to the default environment. This method will copy the environment variables needed for the backends api f...
def UpdateEnv(self, env_dict):
if self.backend_id: env_dict['BACKEND_ID'] = self.backend_id if (self.instance_id is not None): env_dict['INSTANCE_ID'] = str(self.instance_id) for key in os.environ: if key.startswith('BACKEND_PORT'): env_dict[key] = os.environ[key]
'Handles the SocketServer process_request call. If the request is to a backend the request will be handled by a separate thread. If the backend is busy a 503 response will be sent. If this is a balancer instance each incoming request will be forwarded to its own thread and handled there. If no backends are configured t...
def ProcessRequest(self, request, client_address):
assert (not self.IsDefault()) if self.IsBalancer(): ForwardRequestThread(request, client_address).start() return assert (self.IsAppInstance() or self.IsBackendInstance()) if self.handle_requests.Active(): if self.FailFast(): logging.info('respond busy') ...
'Hook that allows the DevProcess a chance to respond to requests. This hook is invoked just before normal request dispatch occurs in dev_appserver.py. Args: request: The request to be handled. Returns: bool: Indicates whether the request was handled here. If False, normal request handling should proceed.'
def HandleRequest(self, request):
if (self.IsBackendInstance() and (not self.started)): if (request.path != '/_ah/start'): request.send_response(httplib.FORBIDDEN, 'Waiting for start request to finish.') return True return False
'Invoked when the process has finished handling a request.'
def RequestComplete(self, request, response):
rc = response.status_code if (request.path == '/_ah/start'): if (((rc >= 200) and (rc < 300)) or (rc == 404)): self.started = True
'Copies info about the backends into the system stub.'
def UpdateSystemStub(self, system_service_stub):
if self.IsDefault(): return system_service_stub.set_backend_info(self.backends)
'Indicates whether this thread is busy handling a request.'
def Active(self):
return self.active
'Adds the indicated request to the pending request queue.'
def Enqueue(self, request, client_address):
self.pending.put_nowait((request, client_address))
'Takes requests from the queue and handles them.'
def run(self):
while True: (request, client_address) = self.pending.get() self.active = True try: HandleRequestDirectly(request, client_address) except Exception as e: logging.info('Exception in HandleRequestThread', exc_info=1) finally: self.active...
'Override.'
def handle_one_request(self):
self.raw_requestline = self.rfile.readline() if (not self.raw_requestline): self.close_connection = 1 return if (not self.parse_request()): return self.send_error(httplib.SERVICE_UNAVAILABLE, 'Busy.')
'Constructor extending BaseHTTPRequestHandler. Args: request: The incoming request. client_address: A (ip, port) tuple with the address of the client. backend: The HTTPServer that received the request. connection_handler: http library to use when balancer the connection to the next available backend instance. Used for ...
def __init__(self, request, client_address, connection_handler=httplib.HTTPConnection):
self.connection_handler = connection_handler BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, HttpServer())
'Override. Invoked from BaseHTTPRequestHandler constructor.'
def handle_one_request(self):
self.raw_requestline = self.rfile.readline() if (not self.raw_requestline): self.close_connection = 1 return if (not self.parse_request()): return process = GlobalProcess() balance_set = process.GetBalanceSet() request_size = int(self.headers.get('content-length', 0)) ...
'Creates a new HttpRpcServerHttpLib2. Args: host: The host to send requests to. auth_function: Saved but ignored; may be used by subclasses. user_agent: The user-agent string to send to the server. Specify None to omit the user-agent header. source: Saved but ignored; may be used by subclasses. host_override: The host ...
def __init__(self, host, auth_function, user_agent, source, host_override=None, extra_headers=None, save_cookies=False, auth_tries=None, account_type=None, debug_data=True, secure=True, ignore_certs=False, rpc_tries=3):
self.host = host self.auth_function = auth_function self.user_agent = user_agent self.source = source self.host_override = host_override self.extra_headers = (extra_headers or {}) self.save_cookies = save_cookies self.auth_tries = auth_tries self.account_type = account_type self....
'Pre or Re-auth stuff... Args: http: An \'Http\' object from httplib2. saw_error: If the user has already tried to contact the server. If they have, it\'s OK to prompt them. If not, we should not be asking them for auth info--it\'s possible it\'ll suceed w/o auth.'
def _Authenticate(self, http, saw_error):
raise NotImplementedError()
'Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for large requests o...
def Send(self, request_path, payload='', content_type='application/octet-stream', timeout=None, **kwargs):
self.http = httplib2.Http(cache=self.memory_cache, ca_certs=self.certpath, disable_ssl_certificate_validation=(not self.cert_file_available)) self.http.follow_redirects = False self.http.timeout = timeout url = ('%s://%s%s' % (self.scheme, self.host, request_path)) if kwargs: url += ('?' + u...
'Creates a new HttpRpcServerOauth2. Args: host: The host to send requests to. refresh_token: A string refresh token to use, or None to guide the user through the auth flow. (Replaces auth_function on parent class.) user_agent: The user-agent string to send to the server. Specify None to omit the user-agent header. sour...
def __init__(self, host, refresh_token, user_agent, source, host_override=None, extra_headers=None, save_cookies=False, auth_tries=None, account_type=None, debug_data=True, secure=True, ignore_certs=False, rpc_tries=3):
super(HttpRpcServerOauth2, self).__init__(host, None, user_agent, None, host_override=host_override, extra_headers=extra_headers, auth_tries=auth_tries, debug_data=debug_data, secure=secure, ignore_certs=ignore_certs, rpc_tries=rpc_tries) if ((not isinstance(source, tuple)) or (len(source) not in (3, 4))): ...
'Pre or Re-auth stuff... This will attempt to avoid making any OAuth related HTTP connections or user interactions unless it\'s needed. Args: http: An \'Http\' object from httplib2. needs_auth: If the user has already tried to contact the server. If they have, it\'s OK to prompt them. If not, we should not be asking th...
def _Authenticate(self, http, needs_auth):
if (needs_auth and ((not self.credentials) or self.credentials.invalid)): if self.refresh_token: logger.debug('_Authenticate and skipping auth because user explicitly supplied a refresh token.') raise AuthPermanentFail('Refresh token is invalid....
'Handles a request for the API Server to exit.'
def _HandleShutdown(self):
self.send_response(httplib.OK) self.send_header('Content-Type', 'text/plain') self.end_headers() self.wfile.write('API Server Quitting') self.server.shutdown()
'Handles a single API request e.g. memcache.Get().'
def do_POST(self):
self.send_response(httplib.OK) self.send_header('Content-Type', 'application/octet-stream') self.end_headers() response = remote_api_pb.Response() try: request = remote_api_pb.Request() request.ParseFromString(self.rfile.read(int(self.headers['content-length']))) api_response...
'Configures the APIs hosted by this server. Args: executable: The path of the executable to use when running the API Server e.g. "/usr/bin/python". host: The host name that should be used by the API Server e.g. "localhost". port: The port number that should be used by the API Server e.g. 8080. app_id: The str applicati...
def __init__(self, executable, host, port, app_id, script=None, application_host=None, application_port=None, application_root=None, auto_id_policy=None, blobstore_path=None, clear_datastore=None, clear_prospective_search=None, datastore_path=None, enable_sendmail=None, enable_task_running=None, high_replication=None, ...
self._process = None self._host = host self._port = port if script: self._args = [executable, script] else: self._args = [executable] self._BindArgument('--api_host', host) self._BindArgument('--api_port', port) self._BindArgument('--application_host', application_host) ...
'Returns the URL that should be used to communicate with the server.'
@property def url(self):
return ('http://%s:%d' % (self._host, self._port))