desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Handle given value based on state of parser
This method handles the various values that are created by the builder
at the beginning of scope events (such as mappings and sequences) or
when a scalar value is received.
Method is called when handler receives a parser, MappingStart or
SequenceStart.
Args:
value: Value rec... | def _HandleValue(self, value):
| (token, top_value) = self._top
if (token == _TOKEN_KEY):
key = self._Pop()
(mapping_token, mapping) = self._top
assert (_TOKEN_MAPPING == mapping_token)
self._builder.MapTo(mapping, key, value)
elif (token == _TOKEN_MAPPING):
self._Push(_TOKEN_KEY, value)
elif (to... |
'Initializes internal state of handler
Args:
event: Ignored.'
| def StreamStart(self, event, loader):
| assert (self._stack is None)
self._stack = []
self._top = None
self._results = []
|
'Cleans up internal state of handler after parsing
Args:
event: Ignored.'
| def StreamEnd(self, event, loader):
| assert ((self._stack == []) and (self._top is None))
self._stack = None
|
'Build new document.
Pushes new document on to stack.
Args:
event: Ignored.'
| def DocumentStart(self, event, loader):
| assert (self._stack == [])
self._Push(_TOKEN_DOCUMENT, self._builder.BuildDocument())
|
'End of document.
Args:
event: Ignored.'
| def DocumentEnd(self, event, loader):
| assert (self._top[0] == _TOKEN_DOCUMENT)
self._results.append(self._Pop())
|
'Not implemented yet.
Args:
event: Ignored.'
| def Alias(self, event, loader):
| raise NotImplementedError('Anchors not supported in this handler')
|
'Handle scalar value
Since scalars are simple values that are passed directly in by the
parser, handle like any value with no additional processing.
Of course, key values will be handles specially. A key value is recognized
when the top token is _TOKEN_MAPPING.
Args:
event: Event containing scalar value.'
| def Scalar(self, event, loader):
| self._HandleAnchor(event)
if ((event.tag is None) and (self._top[0] != _TOKEN_MAPPING)):
try:
tag = loader.resolve(yaml.nodes.ScalarNode, event.value, event.implicit)
except IndexError:
tag = loader.DEFAULT_SCALAR_TAG
else:
tag = event.tag
if (tag is None)... |
'Start of sequence scope
Create a new sequence from the builder and then handle in the context
of its parent.
Args:
event: SequenceStartEvent generated by loader.
loader: Loader that generated event.'
| def SequenceStart(self, event, loader):
| self._HandleAnchor(event)
(token, parent) = self._top
if (token == _TOKEN_KEY):
(token, parent) = self._stack[(-2)]
sequence = self._builder.BuildSequence(parent)
self._HandleValue(sequence)
self._Push(_TOKEN_SEQUENCE, sequence)
|
'End of sequence.
Args:
event: Ignored
loader: Ignored.'
| def SequenceEnd(self, event, loader):
| assert (self._top[0] == _TOKEN_SEQUENCE)
end_object = self._Pop()
top_value = self._top[1]
self._builder.EndSequence(top_value, end_object)
|
'Start of mapping scope.
Create a mapping from builder and then handle in the context of its
parent.
Args:
event: MappingStartEvent generated by loader.
loader: Loader that generated event.'
| def MappingStart(self, event, loader):
| self._HandleAnchor(event)
(token, parent) = self._top
if (token == _TOKEN_KEY):
(token, parent) = self._stack[(-2)]
mapping = self._builder.BuildMapping(parent)
self._HandleValue(mapping)
self._Push(_TOKEN_MAPPING, mapping)
|
'End of mapping
Args:
event: Ignored.
loader: Ignored.'
| def MappingEnd(self, event, loader):
| assert (self._top[0] == _TOKEN_MAPPING)
end_object = self._Pop()
top_value = self._top[1]
self._builder.EndMapping(top_value, end_object)
|
'Get results of document stream processing.
This method can be invoked after fully parsing the entire YAML file
to retrieve constructed contents of YAML file. Called after EndStream.
Returns:
A tuple of all document objects that were parsed from YAML stream.
Raises:
InternalError if the builder stack is not empty by t... | def GetResults(self):
| if (self._stack is not None):
raise yaml_errors.InternalError('Builder stack is not empty.')
return tuple(self._results)
|
'Validates a schedule.'
| def Validate(self, value, key=None):
| if (value is None):
raise validation.MissingAttribute('schedule must be specified')
if (not isinstance(value, basestring)):
raise TypeError(("schedule must be a string, not '%r'" % type(value)))
try:
groctimespecification.GrocTimeSpecification(value)
ex... |
'Validates a timezone.'
| def Validate(self, value, key=None):
| if (value is None):
return
if (not isinstance(value, basestring)):
raise TypeError(("timezone must be a string, not '%r'" % type(value)))
if (pytz is None):
return value
try:
pytz.timezone(value)
except pytz.UnknownTimeZoneError:
raise valida... |
'Constructor.
Args:
default_cpu: SystemStat; if set, value will be used for GetSystemStats.
default_memory: SystemStat; if set, value will be used for GetSystemStats.
request_data: A request_info.RequestInfo instance used to look up state
associated with the request that generated an API call.'
| def __init__(self, default_cpu=None, default_memory=None, request_data=None):
| super(SystemServiceStub, self).__init__('system', request_data=request_data)
self.default_cpu = default_cpu
self.default_memory = default_memory
self.num_calls = {}
self._backend_info = None
|
'Mock version of System stats always returns fixed values.'
| def _Dynamic_GetSystemStats(self, unused_request, response, unused_request_id):
| cpu = response.mutable_cpu()
if self.default_cpu:
cpu.CopyFrom(self.default_cpu)
memory = response.mutable_memory()
if self.default_memory:
memory.CopyFrom(self.default_memory)
self.num_calls['GetSystemStats'] = (self.num_calls.get('GetSystemStats', 0) + 1)
|
'Set backend info. Typically a list of BackendEntry objects.'
| def set_backend_info(self, backend_info):
| self._backend_info = backend_info
|
'Set backend info. Typically a list of BackendEntry objects.'
| def get_backend_info(self):
| return self._backend_info
|
'Initializer.
Args:
prospective_search_path: path for file that persists subscriptions.
taskqueue_stub: taskqueue service stub for returning results.
service_name: Service name expected for all calls.
openfile: function to open the pickled subscription state.'
| def __init__(self, prospective_search_path, taskqueue_stub, service_name='matcher', openfile=open):
| super(ProspectiveSearchStub, self).__init__(service_name)
self.prospective_search_path = prospective_search_path
self.taskqueue_stub = taskqueue_stub
self.topics = {}
self.topics_schema = {}
if os.path.isfile(self.prospective_search_path):
stream = openfile(self.prospective_search_path, ... |
'Persist subscriptions.'
| def _Write(self, openfile=open):
| persisted = openfile(self.prospective_search_path, 'wb')
pickle.dump((self.topics, self.topics_schema), persisted)
persisted.close()
|
'Converts a schema list to a schema dictionary.
Args:
schema_entries: list of SchemaEntry entries.
Returns:
Dictionary mapping field names to SchemaEntry types.'
| def _Get_Schema(self, schema_entries):
| schema = {}
for entry in schema_entries:
schema[entry.name()] = entry.type()
return schema
|
'Subscribe a query.
Args:
request: SubscribeRequest
response: SubscribeResponse (not used)'
| def _Dynamic_Subscribe(self, request, response):
| ValidateSubscriptionId(request.sub_id())
ValidateTopic(request.topic())
ValidateQuery(request.vanilla_query())
schema = self._Get_Schema(request.schema_entry_list())
self.topics_schema[request.topic()] = schema
if (request.lease_duration_sec() == 0):
expires = (time.time() + 4294967295)
... |
'Unsubscribe a query.
Args:
request: UnsubscribeRequest
response: UnsubscribeResponse (not used)'
| def _Dynamic_Unsubscribe(self, request, response):
| ValidateSubscriptionId(request.sub_id())
ValidateTopic(request.topic())
try:
del self.topics[request.topic()][request.sub_id()]
except KeyError:
pass
self._Write()
|
'Remove expired subscriptions.'
| def _ExpireSubscriptions(self):
| now = time.time()
empty_topics = []
for (topic, topic_subs) in self.topics.iteritems():
expired_sub_ids = []
for (sub_id, entry) in topic_subs.iteritems():
(_, expires) = entry
if (expires < now):
expired_sub_ids.append(sub_id)
for sub_id in ex... |
'List subscriptions.
Args:
request: ListSubscriptionsRequest
response: ListSubscriptionsResponse'
| def _Dynamic_ListSubscriptions(self, request, response):
| ValidateTopic(request.topic())
self._ExpireSubscriptions()
topic_subs = self.topics.get(request.topic(), {})
sub_ids = topic_subs.keys()
sub_ids.sort()
start = bisect.bisect_left(sub_ids, request.subscription_id_start())
sub_ids = sub_ids[start:(start + request.max_results())]
for sub_id... |
'List topics.
Args:
request: ListTopicsRequest
response: ListTopicsResponse'
| def _Dynamic_ListTopics(self, request, response):
| topics = self.topics.keys()
topics.sort()
if request.has_topic_start():
start = bisect.bisect_left(topics, request.topic_start())
else:
start = 0
iter_topics = topics[start:(start + request.max_results())]
for topic in iter_topics:
response.topic_list().append(topic)
|
'Deliver list of subscriptions as batches using taskqueue.
Args:
subscriptions: list of subscription ids
match_request: MatchRequest'
| def _DeliverMatches(self, subscriptions, match_request):
| parameters = {'topic': match_request.topic()}
if match_request.has_result_python_document_class():
python_document_class = match_request.result_python_document_class()
parameters['python_document_class'] = python_document_class
parameters['document'] = base64.urlsafe_b64encode(match_requ... |
'Match a document.
Args:
request: MatchRequest
response: MatchResponse (not used)'
| def _Dynamic_Match(self, request, response):
| self._ExpireSubscriptions()
doc = {}
properties = itertools.chain(request.document().property_list(), request.document().raw_property_list())
for prop in properties:
prop_name = unicode(prop.name(), 'utf-8')
doc.setdefault(prop_name, [])
if prop.value().has_int64value():
... |
'Entry point for matching document against a query.'
| def _FindMatches(self, query, doc):
| self._Debug(('_FindMatches: query: %r, doc: %s' % (query, doc)), 0)
query_tree = self._Simplify(query_parser.Parse(unicode(query, 'utf-8')))
match = self._WalkQueryTree(query_tree, doc)
self._Debug(('_FindMatches: result: %s' % match), 0)
return match
|
'Recursive match of doc from query tree at the given node.'
| def _WalkQueryTree(self, query_node, doc, query_field=None, level=0):
| query_type = query_node.getType()
query_text = query_node.getText()
self._Debug(('_WalkQueryTree: query type: %r, field: %r, text: %r' % (query_type, query_field, query_text)), level=level)
if (query_type is QueryParser.CONJUNCTION):
for child in query_node.children:
... |
'Returns true iff \'doc[field_name] op query_val\' evaluates to true.'
| def _MatchField(self, doc, field_name, query_val, op=QueryParser.HAS, level=0):
| field_vals = doc[field_name]
if (type(field_vals) is not list):
field_vals = list(field_vals)
self._Debug(('_MatchField: doc[%s]: %r %s %r' % (field_name, field_vals, op, query_val)), level)
if ((op is QueryParser.HAS) or ((op is QueryParser.EQ) and (type(field_vals[0]) is unicode)))... |
'Simplifies the output of the parser.'
| def _Simplify(self, parser_return):
| if parser_return.tree:
return self._SimplifyNode(query_parser.SimplifyNode(parser_return.tree))
return parser_return
|
'Simplifies the node removing singleton conjunctions and others.'
| def _SimplifyNode(self, node):
| if (not node.getType()):
return self._SimplifyNode(node.children[0])
elif ((node.getType() in query_parser.COMPARISON_TYPES) and (node.getChildCount() is 2) and (node.children[0].getType() is QueryParser.GLOBAL)):
return self._SimplifyNode(node.children[1])
elif (node.getType() is QueryParse... |
'Helper method to print out indented messages.'
| def _Debug(self, msg, level):
| logging.info('%s%s', ''.join((' ' for _ in range(level))), msg)
|
'Constructor.
Args:
storage_directory: Directory within which to store blobs.
app_id: App id to store blobs on behalf of.'
| def __init__(self, storage_directory, app_id):
| self._storage_directory = storage_directory
self._app_id = app_id
|
'Normalize to instance of BlobKey.'
| @classmethod
def _BlobKey(cls, blob_key):
| if (not isinstance(blob_key, blobstore.BlobKey)):
return blobstore.BlobKey(unicode(blob_key))
return blob_key
|
'Determine which directory where a blob is stored.
Each blob gets written to a directory underneath the storage objects
storage directory based on the blobs kind, app-id and first character of
its name. So blobs with blob-keys:
_ACFDEDG
_MNOPQRS
_RSTUVWX
Are stored in:
<storage-dir>/blob/myapp/A
<storage-dir>/blob/mya... | def _DirectoryForBlob(self, blob_key):
| blob_key = self._BlobKey(blob_key)
return os.path.join(self._storage_directory, self._app_id, str(blob_key)[1])
|
'Calculate full filename to store blob contents in.
This method does not check to see if the file actually exists.
Args:
blob_key: Blob key of blob to calculate file for.
Returns:
Complete path for file used for storing blob.'
| def _FileForBlob(self, blob_key):
| blob_key = self._BlobKey(blob_key)
return os.path.join(self._DirectoryForBlob(blob_key), str(blob_key)[1:])
|
'Store blob stream to disk.
Args:
blob_key: Blob key of blob to store.
blob_stream: Stream or stream-like object that will generate blob content.'
| def StoreBlob(self, blob_key, blob_stream):
| blob_key = self._BlobKey(blob_key)
blob_directory = self._DirectoryForBlob(blob_key)
if (not os.path.exists(blob_directory)):
os.makedirs(blob_directory)
blob_file = self._FileForBlob(blob_key)
output = _local_open(blob_file, 'wb')
try:
while True:
block = blob_stream... |
'Open blob file for streaming.
Args:
blob_key: Blob-key of existing blob to open for reading.
Returns:
Open file stream for reading blob from disk.'
| def OpenBlob(self, blob_key):
| return _local_open(self._FileForBlob(blob_key), 'rb')
|
'Delete blob data from disk.
Deleting an unknown blob will not raise an error.
Args:
blob_key: Blob-key of existing blob to delete.'
| def DeleteBlob(self, blob_key):
| try:
os.remove(self._FileForBlob(blob_key))
except OSError as e:
if (e.errno != errno.ENOENT):
raise e
|
'Constructor.'
| def __init__(self):
| self._blobs = {}
|
'Store blob stream.'
| def StoreBlob(self, blob_key, blob_stream):
| content = StringIO.StringIO()
try:
while True:
block = blob_stream.read((1 << 20))
if (not block):
break
content.write(block)
self.CreateBlob(blob_key, content.getvalue())
finally:
content.close()
|
'Store blob in map.'
| def CreateBlob(self, blob_key, blob):
| self._blobs[blobstore.BlobKey(unicode(blob_key))] = blob
|
'Get blob contents as stream.'
| def OpenBlob(self, blob_key):
| return StringIO.StringIO(self._blobs[blobstore.BlobKey(unicode(blob_key))])
|
'Delete blob content.'
| def DeleteBlob(self, blob_key):
| try:
del self._blobs[blobstore.BlobKey(unicode(blob_key))]
except KeyError:
pass
|
'Store blob stream.
Implement this method to persist blob data.
Args:
blob_key: Blob key of blob to store.
blob_stream: Stream or stream-like object that will generate blob content.'
| def StoreBlob(self, blob_key, blob_stream):
| raise NotImplementedError('Storage class must override StoreBlob method.')
|
'Open blob for streaming.
Args:
blob_key: Blob-key of existing blob to open for reading.
Returns:
Open file stream for reading blob. Caller is responsible for closing
file.'
| def OpenBlob(self, blob_key):
| raise NotImplementedError('Storage class must override OpenBlob method.')
|
'Delete blob data from storage.
Args:
blob_key: Blob-key of existing blob to delete.'
| def DeleteBlob(self, blob_key):
| raise NotImplementedError('Storage class must override DeleteBlob method.')
|
'Constructor.
Args:
blob_storage: BlobStorage class instance used for blob storage.
time_function: Used for dependency injection in tests.
service_name: Service name expected for all calls.
uploader_path: Path to upload handler pointed to by URLs generated
by this service stub.
request_data: A apiproxy_stub.RequestData... | def __init__(self, blob_storage, time_function=time.time, service_name='blobstore', uploader_path='_ah/upload/', request_data=None):
| super(BlobstoreServiceStub, self).__init__(service_name, request_data=request_data)
self.__storage = blob_storage
self.__time_function = time_function
self.__next_session_id = 1
self.__uploader_path = uploader_path
self.__block_key_cache = None
|
'Given a string blobkey, return its db.Key.'
| @classmethod
def ToDatastoreBlobKey(cls, blobkey):
| kind = blobstore.BLOB_INFO_KIND
if blobkey.startswith(cls.GS_BLOBKEY_PREFIX):
kind = _GS_INFO_KIND
return datastore_types.Key.from_path(kind, blobkey, namespace='')
|
'Access BlobStorage used by service stub.
Returns:
BlobStorage instance used by blobstore service stub.'
| @property
def storage(self):
| return self.__storage
|
'Helper method ensures environment configured as expected.
Args:
name: Name of environment variable to get.
Returns:
Environment variable associated with name.
Raises:
ConfigurationError if required environment variable is not found.'
| def _GetEnviron(self, name):
| try:
return os.environ[name]
except KeyError:
raise ConfigurationError(('%s is not set in environment.' % name))
|
'Create new upload session.
Args:
success_path: Application path to call upon successful POST.
user: User that initiated the upload session.
max_bytes_per_blob: Maximum number of bytes for any blob in the upload.
max_bytes_total: Maximum aggregate bytes for all blobs in the upload.
bucket_name: The name of the Cloud St... | def _CreateSession(self, success_path, user, max_bytes_per_blob=None, max_bytes_total=None, bucket_name=None):
| return CreateUploadSession(self.__time_function(), success_path, user, max_bytes_per_blob, max_bytes_total, bucket_name)
|
'Create upload URL implementation.
Create a new upload session. The upload session key is encoded in the
resulting POST URL. This URL is embedded in a POST form by the application
which contacts the uploader when the user posts.
Args:
request: A fully initialized CreateUploadURLRequest instance.
response: A CreateUpl... | def _Dynamic_CreateUploadURL(self, request, response, request_id):
| max_bytes_per_blob = None
max_bytes_total = None
bucket_name = None
if request.has_max_upload_size_per_blob_bytes():
max_bytes_per_blob = request.max_upload_size_per_blob_bytes()
if request.has_max_upload_size_bytes():
max_bytes_total = request.max_upload_size_bytes()
if request.... |
'Delete a blob.
Args:
blobkey: blobkey in str.
storage: blobstore storage stub.'
| @classmethod
def DeleteBlob(cls, blobkey, storage):
| storage.DeleteBlob(blobkey)
|
'Delete a blob by its blob-key.
Delete a blob from the blobstore using its blob-key. Deleting blobs that
do not exist is a no-op.
Args:
request: A fully initialized DeleteBlobRequest instance.
response: Not used but should be a VoidProto.'
| def _Dynamic_DeleteBlob(self, request, response, unused_request_id):
| for blobkey in request.blob_key_list():
self.DeleteBlob(blobkey, self.__storage)
|
'Fetch a blob fragment from a blob by its blob-key.
Fetches a blob fragment using its blob-key. Start index is inclusive,
end index is inclusive. Valid requests for information outside of
the range of the blob return a partial string or empty string if entirely
out of range.
Args:
request: A fully initialized FetchDa... | def _Dynamic_FetchData(self, request, response, unused_request_id):
| start_index = request.start_index()
if (start_index < 0):
raise apiproxy_errors.ApplicationError(blobstore_service_pb.BlobstoreServiceError.DATA_INDEX_OUT_OF_RANGE)
end_index = request.end_index()
if (end_index < start_index):
raise apiproxy_errors.ApplicationError(blobstore_service_pb.B... |
'Decode a given blob key: data is simply base64-decoded.
Args:
request: A fully-initialized DecodeBlobKeyRequest instance
response: A DecodeBlobKeyResponse instance.'
| def _Dynamic_DecodeBlobKey(self, request, response, unused_request_id):
| for blob_key in request.blob_key_list():
response.add_decoded(blob_key.decode('base64'))
|
'Create an encoded blob key that represents a Google Storage file.
For now we\'ll just base64 encode the Google Storage filename, APIs that
accept encoded blob keys will need to be able to support Google Storage
files or blobstore files based on decoding this key.
Any stub that creates GS files should use this function... | @classmethod
def CreateEncodedGoogleStorageKey(cls, filename):
| return (cls.GS_BLOBKEY_PREFIX + base64.urlsafe_b64encode(filename))
|
'Create an encoded blob key that represents a Google Storage file.
For now we\'ll just base64 encode the Google Storage filename, APIs that
accept encoded blob keys will need to be able to support Google Storage
files or blobstore files based on decoding this key.
Args:
request: A fully-initialized CreateEncodedGoogleS... | def _Dynamic_CreateEncodedGoogleStorageKey(self, request, response, unused_request_id):
| filename = request.filename()[len(blobstore.GS_PREFIX):]
response.set_blob_key(self.CreateEncodedGoogleStorageKey(filename))
|
'Create new blob and put in storage and Datastore.
This is useful in testing where you have access to the stub.
Args:
blob_key: String blob-key of new blob.
content: Content of new blob as a string.
Returns:
New Datastore entity without blob meta-data fields.'
| def CreateBlob(self, blob_key, content):
| entity = datastore.Entity(blobstore.BLOB_INFO_KIND, name=blob_key, namespace='')
entity['size'] = len(content)
datastore.Put(entity)
self.storage.CreateBlob(blob_key, content)
return entity
|
'Constructor.
Args:
app_id: App id to store blobs on behalf of.'
| def __init__(self, app_id):
| self._app_id = app_id
|
'Normalize to instance of BlobKey.
Args:
blob_key: A blob key of a blob to store.
Returns:
A normalized blob key of class BlobKey.'
| @classmethod
def _BlobKey(cls, blob_key):
| if (not isinstance(blob_key, blobstore.BlobKey)):
return blobstore.BlobKey(unicode(blob_key))
return blob_key
|
'Store blob stream to the datastore.
Args:
blob_key: Blob key of blob to store.
blob_stream: Stream or stream-like object that will generate blob content.'
| def StoreBlob(self, blob_key, blob_stream):
| block_count = 0
blob_key_object = self._BlobKey(blob_key)
while True:
block = blob_stream.read(blobstore.MAX_BLOB_FETCH_SIZE)
if (not block):
break
entity = datastore.Entity(_BLOB_CHUNK_KIND_, name=((str(blob_key_object) + '__') + str(block_count)), namespace='')
... |
'Open blob file for streaming.
Args:
blob_key: Blob-key of existing blob to open for reading.
Returns:
Open file stream for reading blob from the datastore.'
| def OpenBlob(self, blob_key):
| return BlobReader(blob_key, blobstore.MAX_BLOB_FETCH_SIZE, 0)
|
'Delete blob data from the datastore.
Args:
blob_key: Blob-key of existing blob to delete.
Raises:
ApplicationError: When a blob is not found or unable to be read.'
| def DeleteBlob(self, blob_key):
| blob_info_key = datastore.Key.from_path(blobstore.BLOB_INFO_KIND, str(blob_key), namespace='')
try:
blob_info = datastore.Get(blob_info_key)
except datastore_errors.EntityNotFoundError:
raise apiproxy_errors.ApplicationError(blobstore_service_pb.BlobstoreServiceError.BLOB_NOT_FOUND)
bloc... |
'Returns a list of module names.'
| def get_module_names(self):
| raise NotImplementedError()
|
'Returns a list of versions for a module.
Args:
module: A str containing the name of the module.
Returns:
A list of str containing the versions for the specified module.
Raises:
ModuleDoesNotExistError: The module does not exist.'
| def get_versions(self, module):
| raise NotImplementedError()
|
'Returns the default version for a module.
Args:
module: A str containing the name of the module.
Returns:
A str containing the default version for the specified module.
Raises:
ModuleDoesNotExistError: The module does not exist.'
| def get_default_version(self, module):
| raise NotImplementedError()
|
'Returns the hostname for a (module, version, instance) tuple.
If instance is set, this will return a hostname for that particular
instances. Otherwise, it will return the hostname for load-balancing.
Args:
module: A str containing the name of the module.
version: A str containing the version.
instance: An optional str... | def get_hostname(self, module, version, instance=None):
| raise NotImplementedError()
|
'Sets the number of instances to run for a version of a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
instances: An int containing the number of instances to run.
Raises:
ModuleDoesNotExistError: The module does not exist.
VersionDoesNotExistError: The version doe... | def set_num_instances(self, module, version, instances):
| raise NotImplementedError()
|
'Gets the number of instances running for a version of a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
Raises:
ModuleDoesNotExistError: The module does not exist.
VersionDoesNotExistError: The version does not exist.
NotSupportedWithAutoScalingError: The provided ... | def get_num_instances(self, module, version):
| raise NotImplementedError()
|
'Starts a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
Raises:
ModuleDoesNotExistError: The module does not exist.
VersionDoesNotExistError: The version does not exist.
NotSupportedWithAutoScalingError: The provided module/version uses
automatic scaling.'
| def start_module(self, module, version):
| raise NotImplementedError()
|
'Stops a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
Raises:
ModuleDoesNotExistError: The module does not exist.
VersionDoesNotExistError: The version does not exist.
NotSupportedWithAutoScalingError: The provided module/version uses
automatic scaling.'
| def stop_module(self, module, version):
| raise NotImplementedError()
|
'Add a callable to be run at the specified time.
Args:
runnable: A callable object to call at the specified time.
eta: An int containing the time to run the event, in seconds since the
epoch.
service: A str containing the name of the service that owns this event.
This should be set if event_id is set.
event_id: A str c... | def add_event(self, runnable, eta, service=None, event_id=None):
| raise NotImplementedError()
|
'Update the eta of a scheduled event.
Args:
eta: An int containing the time to run the event, in seconds since the
epoch.
service: A str containing the name of the service that owns this event.
event_id: A str containing the id of the event to update.'
| def update_event(self, eta, service, event_id):
| raise NotImplementedError()
|
'Process an HTTP request.
Args:
method: A str containing the HTTP method of the request.
relative_url: A str containing path and query string of the request.
headers: A list of (key, value) tuples where key and value are both str.
body: A str containing the request body.
source_ip: The source ip address for the request... | def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None):
| raise NotImplementedError()
|
'Dispatch an HTTP request asynchronously.
Args:
method: A str containing the HTTP method of the request.
relative_url: A str containing path and query string of the request.
headers: A list of (key, value) tuples where key and value are both str.
body: A str containing the request body.
source_ip: The source ip address... | def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None):
| raise NotImplementedError()
|
'Dispatch a background thread request.
Args:
module_name: A str containing the module name to service this
request.
version: A str containing the version to service this request.
instance: The instance to service this request.
background_request_id: A str containing the unique background thread
request identifier.
Rais... | def send_background_request(self, module_name, version, instance, background_request_id):
| raise NotImplementedError()
|
'Returns a list of module names.'
| def get_module_names(self):
| return self._module_names
|
'Returns a list of versions for a module.
Args:
module: A str containing the name of the module.
Returns:
A list of str containing the versions for the specified module.
Raises:
ModuleDoesNotExistError: The module does not exist.'
| def get_versions(self, module):
| if (module not in self._module_name_to_versions):
raise ModuleDoesNotExistError()
return self._module_name_to_versions[module]
|
'Returns the default version for a module.
Args:
module: A str containing the name of the module.
Returns:
A str containing the default version for the specified module.
Raises:
ModuleDoesNotExistError: The module does not exist.'
| def get_default_version(self, module):
| if (module not in self._module_name_to_default_versions):
raise ModuleDoesNotExistError()
return self._module_name_to_default_versions[module]
|
'Returns the hostname for a (module, version, instance) tuple.
If instance is set, this will return a hostname for that particular
instances. Otherwise, it will return the hostname for load-balancing.
Args:
module: A str containing the name of the module.
version: A str containing the version.
instance: An optional str... | def get_hostname(self, module, version, instance=None):
| if (module not in self._module_name_to_version_to_hostname):
raise ModuleDoesNotExistError()
if (version not in self._module_name_to_version_to_hostname[module]):
raise VersionDoesNotExistError()
if instance:
raise InvalidInstanceIdError()
return self._module_name_to_version_to_h... |
'Sets the number of instances to run for a version of a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
instances: An int containing the number of instances to run.
Raises:
ModuleDoesNotExistError: The module does not exist.
VersionDoesNotExistError: The version doe... | def set_num_instances(self, module, version, instances):
| if (module not in self._module_name_to_versions):
raise ModuleDoesNotExistError()
if (version not in self._module_name_to_versions[module]):
raise VersionDoesNotExistError()
raise NotSupportedWithAutoScalingError()
|
'Gets the number of instances running for a version of a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
Raises:
ModuleDoesNotExistError: The module does not exist.
VersionDoesNotExistError: The version does not exist.
NotSupportedWithAutoScalingError: The provided ... | def get_num_instances(self, module, version):
| if (module not in self._module_name_to_versions):
raise ModuleDoesNotExistError()
if (version not in self._module_name_to_versions[module]):
raise VersionDoesNotExistError()
raise NotSupportedWithAutoScalingError()
|
'Starts a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
Raises:
ModuleDoesNotExistError: The module does not exist.
VersionDoesNotExistError: The version does not exist.
NotSupportedWithAutoScalingError: The provided module/version uses
automatic scaling.'
| def start_module(self, module, version):
| if (module not in self._module_name_to_versions):
raise ModuleDoesNotExistError()
if (version not in self._module_name_to_versions[module]):
raise VersionDoesNotExistError()
raise NotSupportedWithAutoScalingError()
|
'Stops a module.
Args:
module: A str containing the name of the module.
version: A str containing the version.
Raises:
ModuleDoesNotExistError: The module does not exist.
VersionDoesNotExistError: The version does not exist.
NotSupportedWithAutoScalingError: The provided module/version uses
automatic scaling.'
| def stop_module(self, module, version):
| if (module not in self._module_name_to_versions):
raise ModuleDoesNotExistError()
if (version not in self._module_name_to_versions[module]):
raise VersionDoesNotExistError()
raise NotSupportedWithAutoScalingError()
|
'Add a callable to be run at the specified time.
Args:
runnable: A callable object to call at the specified time.
eta: An int containing the time to run the event, in seconds since the
epoch.
service: A str containing the name of the service that owns this event.
This should be set if event_id is set.
event_id: A str c... | def add_event(self, runnable, eta, service=None, event_id=None):
| logging.warning('Scheduled events are not supported with _LocalFakeDispatcher')
|
'Update the eta of a scheduled event.
Args:
eta: An int containing the time to run the event, in seconds since the
epoch.
service: A str containing the name of the service that owns this event.
event_id: A str containing the id of the event to update.'
| def update_event(self, eta, service, event_id):
| logging.warning('Scheduled events are not supported with _LocalFakeDispatcher')
|
'Process an HTTP request.
Args:
method: A str containing the HTTP method of the request.
relative_url: A str containing path and query string of the request.
headers: A list of (key, value) tuples where key and value are both str.
body: A str containing the request body.
source_ip: The source ip address for the request... | def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None):
| logging.warning('Request dispatching is not supported with _LocalFakeDispatcher')
return ResponseTuple('501 Not Implemented', [], '')
|
'Dispatch an HTTP request asynchronously.
Args:
method: A str containing the HTTP method of the request.
relative_url: A str containing path and query string of the request.
headers: A list of (key, value) tuples where key and value are both str.
body: A str containing the request body.
source_ip: The source ip address... | def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None):
| logging.warning('Request dispatching is not supported with _LocalFakeDispatcher')
|
'Dispatch a background thread request.
Args:
module_name: A str containing the module name to service this
request.
version: A str containing the version to service this request.
instance: The instance to service this request.
background_request_id: A str containing the unique background thread
request identifier.
Rais... | def send_background_request(self, module_name, version, instance, background_request_id):
| logging.warning('Request dispatching is not supported with _LocalFakeDispatcher')
raise BackgroundThreadLimitReachedError()
|
'Returns the URL the request e.g. \'http://localhost:8080/foo?bar=baz\'.
Args:
request_id: The string id of the request making the API call.
Returns:
The URL of the request as a string.'
| def get_request_url(self, request_id):
| raise NotImplementedError()
|
'Returns a dict containing the WSGI environ for the request.'
| def get_request_environ(self, request_id):
| raise NotImplementedError()
|
'Returns the name of the module serving this request.
Args:
request_id: The string id of the request making the API call.
Returns:
A str containing the module name.'
| def get_module(self, request_id):
| raise NotImplementedError()
|
'Returns the version of the module serving this request.
Args:
request_id: The string id of the request making the API call.
Returns:
A str containing the version.'
| def get_version(self, request_id):
| raise NotImplementedError()
|
'Returns the instance serving this request.
Args:
request_id: The string id of the request making the API call.
Returns:
An opaque representation of the instance serving this request. It should
only be passed to dispatcher methods expecting an instance.'
| def get_instance(self, request_id):
| raise NotImplementedError()
|
'Returns the Dispatcher.
Returns:
The Dispatcher instance.'
| def get_dispatcher(self):
| raise NotImplementedError()
|
'Returns the URL the request e.g. \'http://localhost:8080/foo?bar=baz\'.
Args:
request_id: The string id of the request making the API call.
Returns:
The URL of the request as a string.'
| def get_request_url(self, request_id):
| try:
host = os.environ['HTTP_HOST']
except KeyError:
host = os.environ['SERVER_NAME']
port = os.environ['SERVER_PORT']
if (port != '80'):
host += (':' + port)
url = ('http://' + host)
url += urllib.quote(os.environ.get('PATH_INFO', '/'))
if os.environ.get(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.