desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Adds tasks to the appropriate DummyTaskStore. Args: request: The taskqueue_service_pb.TaskQueueBulkAddRequest containing the tasks to add. N.B. all tasks in the request have been validated and those with empty names have been assigned unique names. response: The taskqueue_service_pb.TaskQueueBulkAddResponse to populat...
def _DummyTaskStoreBulkAdd(self, request, response):
store = self.GetDummyTaskStore(request.add_request(0).app_id(), request.add_request(0).queue_name()) for (add_request, task_result) in zip(request.add_request_list(), response.taskresult_list()): try: store.Add(add_request) except apiproxy_errors.ApplicationError as e: ta...
'Adds tasks to the appropriate list in in self._taskqueues. Args: request: The taskqueue_service_pb.TaskQueueBulkAddRequest containing the tasks to add. N.B. all tasks in the request have been validated and those with empty names have been assigned unique names. response: The taskqueue_service_pb.TaskQueueBulkAddRespon...
def _NonTransactionalBulkAdd(self, request, response):
existing_tasks = self._taskqueues.setdefault(request.add_request(0).queue_name(), []) existing_task_names = set((task.task_name() for task in existing_tasks)) def DefineCallback(queue_name, task_name): return (lambda : self._RunTask(queue_name, task_name)) for (add_request, task_result) in zip(r...
'Determines whether a queue is valid, i.e. tasks can be added to it. Valid queues are the \'default\' queue, plus any queues in the queue.yaml file. Args: queue_name: the name of the queue to validate. app_id: the app_id. Can be None. Returns: True iff queue is valid.'
def _IsValidQueue(self, queue_name, app_id):
if self._all_queues_valid: return True if ((queue_name == DEFAULT_QUEUE_NAME) or (queue_name == CRON_QUEUE_NAME)): return True queue_info = self.queue_yaml_parser(self._root_path) if (queue_info and queue_info.queue): for entry in queue_info.queue: if (entry.name == q...
'Returns a fake request for running a task in the dev_appserver. Args: queue_name: The queue the task is in. task_name: The name of the task to run. Returns: None if this task no longer exists or tuple (connection, addrinfo) of a fake connection and address information used to run this task. The task will be deleted af...
def _RunTask(self, queue_name, task_name):
task_list = self.GetTasks(queue_name) for task in task_list: if (task['name'] == task_name): break else: return None class FakeConnection(object, ): def __init__(self, input_buffer): self.rfile = StringIO.StringIO(input_buffer) self.wfile = Str...
'Gets all the applications\'s queues. Returns: A list of dictionaries, where each dictionary contains one queue\'s attributes. E.g.: [{\'name\': \'some-queue\', \'max_rate\': \'1/s\', \'bucket_size\': 5, \'oldest_task\': \'2009/02/02 05:37:42\', \'eta_delta\': \'0:00:06.342511 ago\', \'tasks_in_queue\': 12}, ...] The l...
def GetQueues(self):
queues = [] queue_info = self.queue_yaml_parser(self._root_path) has_default = False if (queue_info and queue_info.queue): for entry in queue_info.queue: if (entry.name == DEFAULT_QUEUE_NAME): has_default = True queue = {} queues.append(queue) ...
'Gets a queue\'s tasks. Args: queue_name: Queue\'s name to return tasks for. Returns: A list of dictionaries, where each dictionary contains one task\'s attributes. E.g. [{\'name\': \'task-123\', \'queue_name\': \'default\', \'url\': \'/update\', \'method\': \'GET\', \'eta\': \'2009/02/02 05:37:42\', \'eta_delta\': \'0...
def GetTasks(self, queue_name):
tasks = self._taskqueues.get(queue_name, []) result_tasks = [] for task_request in tasks: task = {} result_tasks.append(task) task['name'] = task_request.task_name() task['queue_name'] = queue_name task['url'] = task_request.url() method = task_request.method(...
'Deletes a task from a queue. Args: queue_name: the name of the queue to delete the task from. task_name: the name of the task to delete.'
def DeleteTask(self, queue_name, task_name):
tasks = self._taskqueues.get(queue_name, []) for task in tasks: if (task.task_name() == task_name): tasks.remove(task) return
'Removes all tasks from a queue. Args: queue_name: the name of the queue to remove tasks from.'
def FlushQueue(self, queue_name):
self._taskqueues[queue_name] = []
'Local implementation of the UpdateQueue RPC in TaskQueueService. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueueUpdateQueueRequest. unused_response: A taskqueue_service_pb.TaskQueueUp...
def _Dynamic_UpdateQueue(self, request, unused_response):
queues = self._app_queues.setdefault(request.app_id(), {}) if ((request.queue_name() in queues) and (queues[request.queue_name()] is None)): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.TOMBSTONED_QUEUE) defensive_copy = self._QueueDetails() defensive_copy.Co...
'Local implementation of the FetchQueues RPC in TaskQueueService. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A taskqueue_service_pb.TaskQueueFetchQueuesRequest. response: A taskqueue_service_pb.TaskQueueFetchQueu...
def _Dynamic_FetchQueues(self, request, response):
queues = self._app_queues.get(request.app_id(), {}) for (unused_key, queue) in sorted(queues.items()): if (request.max_rows() == response.queue_size()): break if (queue is None): continue response_queue = response.add_queue() response_queue.set_queue_name(...
'Local \'random\' implementation of the TaskQueueService.FetchQueueStats. This implementation loads some stats from the dummy store, the rest with random numbers. Must adhere to the \'_Dynamic_\' naming convention for stubbing to work. See taskqueue_service.proto for a full description of the RPC. Args: request: A task...
def _Dynamic_FetchQueueStats(self, request, response):
for queue in request.queue_name_list(): store = self.GetDummyTaskStore(request.app_id(), queue) stats = response.add_queuestats() stats.set_num_tasks(store.Count()) if (stats.num_tasks() == 0): stats.set_oldest_eta_usec((-1)) else: stats.set_oldest_eta...
'Get the dummy task store for this app_id/queue_name pair. Creates an entry and populates it, if there\'s not already an entry. Args: app_id: the app_id. queue_name: the queue_name. Returns: the existing or the new dummy store.'
def GetDummyTaskStore(self, app_id, queue_name):
task_store_key = (app_id, queue_name) if (task_store_key not in admin_console_dummy_tasks): store = _DummyTaskStore() if ((not self._all_queues_valid) and (queue_name != CRON_QUEUE_NAME)): store.Populate(random.randint(10, 100)) admin_console_dummy_tasks[task_store_key] = sto...
'Local implementation of the TaskQueueService.QueryTasks RPC. Uses the dummy store, creating tasks if this is the first time the queue has been seen. Args: request: A taskqueue_service_pb.TaskQueueQueryTasksRequest. response: A taskqueue_service_pb.TaskQueueQueryTasksResponse.'
def _Dynamic_QueryTasks(self, request, response):
store = self.GetDummyTaskStore(request.app_id(), request.queue_name()) if request.has_start_eta_usec(): tasks = store.Lookup(request.max_rows(), name=request.start_task_name(), eta=request.start_eta_usec()) else: tasks = store.Lookup(request.max_rows(), name=request.start_task_name()) fo...
'Local delete implementation of TaskQueueService.Delete. Deletes tasks from the dummy store. A 1/20 chance of a transient error. Args: request: A taskqueue_service_pb.TaskQueueDeleteRequest. response: A taskqueue_service_pb.TaskQueueDeleteResponse.'
def _Dynamic_Delete(self, request, response):
task_store_key = (request.app_id(), request.queue_name()) if (task_store_key not in admin_console_dummy_tasks): for _ in request.task_name_list(): response.add_result(taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_QUEUE) return store = admin_console_dummy_tasks[task_store...
'Local force run implementation of TaskQueueService.ForceRun. Forces running of a task in a queue. This is a no-op here. This will fail randomly for testing. Args: request: A taskqueue_service_pb.TaskQueueForceRunRequest. response: A taskqueue_service_pb.TaskQueueForceRunResponse.'
def _Dynamic_ForceRun(self, request, response):
if (random.random() <= 0.05): response.set_result(taskqueue_service_pb.TaskQueueServiceError.TRANSIENT_ERROR) elif (random.random() <= 0.052): response.set_result(taskqueue_service_pb.TaskQueueServiceError.INTERNAL_ERROR) else: response.set_result(taskqueue_service_pb.TaskQueueServic...
'Local delete implementation of TaskQueueService.DeleteQueue. Args: request: A taskqueue_service_pb.TaskQueueDeleteQueueRequest. response: A taskqueue_service_pb.TaskQueueDeleteQueueResponse.'
def _Dynamic_DeleteQueue(self, request, response):
if (not request.queue_name()): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INVALID_QUEUE_NAME) queues = self._app_queues.get(request.app_id(), {}) if (request.queue_name() not in queues): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQu...
'Local pause implementation of TaskQueueService.PauseQueue. Args: request: A taskqueue_service_pb.TaskQueuePauseQueueRequest. response: A taskqueue_service_pb.TaskQueuePauseQueueResponse.'
def _Dynamic_PauseQueue(self, request, response):
if (not request.queue_name()): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INVALID_QUEUE_NAME) queues = self._app_queues.get(request.app_id(), {}) if (request.queue_name() != DEFAULT_QUEUE_NAME): if (request.queue_name() not in queues): raise...
'Local purge implementation of TaskQueueService.PurgeQueue. Args: request: A taskqueue_service_pb.TaskQueuePurgeQueueRequest. response: A taskqueue_service_pb.TaskQueuePurgeQueueResponse.'
def _Dynamic_PurgeQueue(self, request, response):
if (not request.queue_name()): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INVALID_QUEUE_NAME) if request.has_app_id(): queues = self._app_queues.get(request.app_id(), {}) if (request.queue_name() != DEFAULT_QUEUE_NAME): if (request.queue...
'Local delete implementation of TaskQueueService.DeleteGroup. Args: request: A taskqueue_service_pb.TaskQueueDeleteGroupRequest. response: A taskqueue_service_pb.TaskQueueDeleteGroupResponse.'
def _Dynamic_DeleteGroup(self, request, response):
queues = self._app_queues.get(request.app_id(), {}) for queue in queues.iterkeys(): store = self.GetDummyTaskStore(request.app_id(), queue) for task in store.Lookup(store.Count()): store.Delete(task.task_name()) self.FlushQueue(queue) self._app_queues[request.app_id()] = ...
'Local implementation of TaskQueueService.UpdateStorageLimit. Args: request: A taskqueue_service_pb.TaskQueueUpdateStorageLimitRequest. response: A taskqueue_service_pb.TaskQueueUpdateStorageLimitResponse.'
def _Dynamic_UpdateStorageLimit(self, request, response):
if ((request.limit() < 0) or (request.limit() > (1000 * (1024 ** 4)))): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INVALID_REQUEST) response.set_new_limit(request.limit())
'Initialize exception.'
def __init__(self, message, cause=None):
if (hasattr(cause, 'args') and cause.args): Error.__init__(self, message, *cause.args) else: Error.__init__(self, message) self.message = message self.cause = cause
'Safely get the Validator corresponding to the given key. This function should be overridden by subclasses Args: key: The attribute or item to get a validator for. Returns: Validator associated with key or attribute. Raises: ValidationError if the requested key is illegal.'
@classmethod def GetValidator(self, key):
raise NotImplementedError('Subclasses of ValidatedBase must override GetValidator.')
'Set multiple values on Validated instance. All attributes will be validated before being set. Args: attributes: A dict of attributes/items to set. Raises: ValidationError when no validated attribute exists on class.'
def SetMultiple(self, attributes):
for (key, value) in attributes.iteritems(): self.Set(key, value)
'Set a single value on Validated instance. This method should be overridded by sub-classes. This method can only be used to assign validated attributes/items. Args: key: The name of the attributes value: The value to set Raises: ValidationError when no validated attribute exists on class.'
def Set(self, key, value):
raise NotImplementedError('Subclasses of ValidatedBase must override Set.')
'Checks that all required fields are initialized. This function is called after all attributes have been checked to verify any higher level constraints, for example ensuring all required attributes are present. Subclasses should override this function and raise an exception for any errors.'
def CheckInitialized(self):
pass
'Convert ValidatedBase object to a dictionary. Recursively traverses all of its elements and converts everything to simplified collections. Subclasses should override this method. Returns: A dictionary mapping all attributes to simple values or collections.'
def ToDict(self):
raise NotImplementedError('Subclasses of ValidatedBase must override ToDict.')
'Print validated object as simplified YAML. Returns: Object as a simplified YAML string compatible with parsing using the SafeLoader.'
def ToYAML(self):
return yaml.dump(self.ToDict(), default_flow_style=False, Dumper=yaml.SafeDumper)
'Constructor for Validated classes. This constructor can optionally assign values to the class via its keyword arguments. Raises: AttributeDefinitionError when class instance is missing ATTRIBUTE definition or when ATTRIBUTE is of the wrong type.'
def __init__(self, **attributes):
if (not isinstance(self.ATTRIBUTES, dict)): raise AttributeDefinitionError(('The class %s does not define an ATTRIBUTE variable.' % self.__class__)) for key in self.ATTRIBUTES.keys(): object.__setattr__(self, key, self.GetValidator(key).default) self.SetMultiple(attri...
'Safely get the underlying attribute definition as a Validator. Args: key: Name of attribute to get. Returns: Validator associated with key or attribute value wrapped in a validator.'
@classmethod def GetValidator(self, key):
if (key not in self.ATTRIBUTES): raise ValidationError(("Unexpected attribute '%s' for object of type %s." % (key, self.__name__))) return AsValidator(self.ATTRIBUTES[key])
'Set a single value on Validated instance. This method can only be used to assign validated attributes. Args: key: The name of the attributes value: The value to set Raises: ValidationError when no validated attribute exists on class.'
def Set(self, key, value):
setattr(self, key, value)
'Get a single value on Validated instance. This method can only be used to retrieve validated attributes. Args: key: The name of the attributes Raises: ValidationError when no validated attribute exists on class.'
def Get(self, key):
self.GetValidator(key) return getattr(self, key)
'Checks that all required fields are initialized. Since an instance of Validated starts off in an uninitialized state, it is sometimes necessary to check that it has been fully initialized. The main problem this solves is how to validate that an instance has all of its required fields set. By default, Validator classe...
def CheckInitialized(self):
for key in self.ATTRIBUTES.iterkeys(): try: self.GetValidator(key)(getattr(self, key)) except MissingAttribute as e: e.message = ("Missing required value '%s'." % key) raise e
'Set attribute. Setting a value on an object of this type will only work for attributes defined in ATTRIBUTES. To make other assignments possible it is necessary to override this method in subclasses. It is important that assignment is restricted in this way because this validation is used as validation for parsing. ...
def __setattr__(self, key, value):
value = self.GetValidator(key)(value, key) object.__setattr__(self, key, value)
'Formatted view of validated object and nested values.'
def __str__(self):
return repr(self)
'Formatted view of validated object and nested values.'
def __repr__(self):
values = [(attr, getattr(self, attr)) for attr in self.ATTRIBUTES] dent = ' ' value_list = [] for (attr, value) in values: value_list.append(('\n%s%s=%s' % (dent, attr, value))) return ('<%s %s\n%s>' % (self.__class__.__name__, ' '.join(value_list), dent))
'Equality operator. Comparison is done by comparing all attribute values to those in the other instance. Objects which are not of the same type are not equal. Args: other: Other object to compare against. Returns: True if validated objects are equal, else False.'
def __eq__(self, other):
if (type(self) != type(other)): return False for key in self.ATTRIBUTES.iterkeys(): if (getattr(self, key) != getattr(other, key)): return False return True
'Inequality operator.'
def __ne__(self, other):
return (not self.__eq__(other))
'Hash function for using Validated objects in sets and maps. Hash is done by hashing all keys and values and xor\'ing them together. Returns: Hash of validated object.'
def __hash__(self):
result = 0 for key in self.ATTRIBUTES.iterkeys(): value = getattr(self, key) if isinstance(value, list): value = tuple(value) result = ((result ^ hash(key)) ^ hash(value)) return result
'Convert Validated object to a dictionary. Recursively traverses all of its elements and converts everything to simplified collections. Returns: A dict of all attributes defined in this classes ATTRIBUTES mapped to its value. This structure is recursive in that Validated objects that are referenced by this object and ...
def ToDict(self):
result = {} for (name, validator) in self.ATTRIBUTES.iteritems(): value = getattr(self, name) if (not (isinstance(validator, Validator) and (value == validator.default))): result[name] = _SimplifiedValue(validator, value) return result
'Construct a validated dict by interpreting the key and value validators. Args: **kwds: keyword arguments will be validated and put into the dict.'
def __init__(self, **kwds):
self.update(kwds)
'Check the key for validity and return a corresponding value validator. Args: key: The key that will correspond to the validator we are returning.'
@classmethod def GetValidator(self, key):
key = AsValidator(self.KEY_VALIDATOR)(key, ('key in %s' % self.__name__)) return AsValidator(self.VALUE_VALIDATOR)
'Set an item. Only attributes accepted by GetValidator and values that validate with the validator returned from GetValidator are allowed to be set in this dictionary. Args: key: Name of item to set. value: Items new value. Raises: ValidationError when trying to assign to a value that does not exist.'
def __setitem__(self, key, value):
dict.__setitem__(self, key, self.GetValidator(key)(value, key))
'Trap setdefaultss to ensure all key/value pairs are valid. See the documentation for setdefault on dict for usage details. Raises: ValidationError if the specified key is illegal or the value invalid.'
def setdefault(self, key, value=None):
return dict.setdefault(self, key, self.GetValidator(key)(value, key))
'Trap updates to ensure all key/value pairs are valid. See the documentation for update on dict for usage details. Raises: ValidationError if any of the specified keys are illegal or values invalid.'
def update(self, other, **kwds):
if (hasattr(other, 'keys') and callable(getattr(other, 'keys'))): newother = {} for k in other: newother[k] = self.GetValidator(k)(other[k], k) else: newother = [(k, self.GetValidator(k)(v, k)) for (k, v) in other] newkwds = {} for k in kwds: newkwds[k] = self...
'Set a single value on Validated instance. This method checks that a given key and value are valid and if so puts the item into this dictionary. Args: key: The name of the attributes value: The value to set Raises: ValidationError when no validated attribute exists on class.'
def Set(self, key, value):
self[key] = value
'Convert ValidatedBase object to a dictionary. Recursively traverses all of its elements and converts everything to simplified collections. Subclasses should override this method. Returns: A dictionary mapping all attributes to simple values or collections.'
def ToDict(self):
result = {} for (name, value) in self.iteritems(): validator = self.GetValidator(name) result[name] = _SimplifiedValue(validator, value) return result
'Constructor. Args: default: Default assignment is made during initialization and will not pass through validation.'
def __init__(self, default=None):
self.default = default
'Main interface to validator is call mechanism.'
def __call__(self, value, key='???'):
return self.Validate(value, key)
'Override this method to customize sub-class behavior. Args: value: Value to validate. key: Name of the field being validated. Returns: Value if value is valid, or a valid representation of value.'
def Validate(self, value, key='???'):
return value
'Convert \'value\' to a simplified collection or basic type. Subclasses of Validator should override this method when the dumped representation of \'value\' is not simply <type>(value) (e.g. a regex). Args: value: An object of the same type that was returned from Validate(). Returns: An instance of a builtin type (e.g....
def ToValue(self, value):
return value
'Initialize Type validator. Args: expected_type: Type that attribute should validate against. convert: Cause conversion if value is not the right type. Conversion is done by calling the constructor of the type with the value as its first parameter. default: Default assignment is made during initialization and will not ...
def __init__(self, expected_type, convert=True, default=None):
super(Type, self).__init__(default) self.expected_type = expected_type self.convert = convert
'Validate that value has the correct type. Args: value: Value to validate. key: Name of the field being validated. Returns: value if value is of the correct type. value is coverted to the correct type if the Validator is configured to do so. Raises: MissingAttribute: if value is None and the expected type is not NoneTy...
def Validate(self, value, key):
if (not isinstance(value, self.expected_type)): if (value is None): raise MissingAttribute('Missing value is required.') if self.convert: try: return self.expected_type(value) except ValueError as e: raise ValidationError((...
'Initialize options. Args: options: List of allowed values.'
def __init__(self, *options, **kw):
if ('default' in kw): default = kw['default'] else: default = None alias_map = {} def AddAlias(alias, original): 'Set new alias on alias_map.\n\n Raises:\n AttributeDefinitionError when option already e...
'Validate options. Returns: Original value for provided alias. Raises: ValidationError when value is not one of predefined values.'
def Validate(self, value, key):
if (value is None): raise ValidationError('Value for options field must not be None.') value = str(value) if (value not in self.options): raise ValidationError(("Value '%s' for %s not in %s." % (value, key, self.options))) return self.options[value]...
'Initializer. This constructor will make a few guesses about the value passed in as the validator: - If the validator argument is a type, it automatically creates a Type validator around it. - If the validator argument is a list or tuple, it automatically creates an Options validator around it. Args: validator: Optiona...
def __init__(self, validator, default=None):
self.validator = AsValidator(validator) self.expected_type = self.validator.expected_type self.default = default
'Optionally require a value. Normal validators do not accept None. This will accept none on behalf of the contained validator. Args: value: Value to be validated as optional. key: Name of the field being validated. Returns: None if value is None, else results of contained validation.'
def Validate(self, value, key):
if (value is None): return None return self.validator(value, key)
'Convert \'value\' to a simplified collection or basic type.'
def ToValue(self, value):
if (value is None): return None return self.validator.ToValue(value)
'Initialized regex validator. Args: regex: Regular expression string to use for comparison. Raises: AttributeDefinitionError if string_type is not a kind of string.'
def __init__(self, regex, string_type=unicode, default=None):
super(Regex, self).__init__(default) if ((not issubclass(string_type, basestring)) or (string_type is basestring)): raise AttributeDefinitionError(('Regex fields must be a string type not %s.' % str(string_type))) if isinstance(regex, basestring): self.re = re.compile...
'Does validation of a string against a regular expression. Args: value: String to match against regular expression. key: Name of the field being validated. Raises: ValidationError when value does not match regular expression or when value does not match provided string type.'
def Validate(self, value, key):
if issubclass(self.expected_type, str): cast_value = TYPE_STR(value) else: cast_value = TYPE_UNICODE(value) if (self.re.match(cast_value) is None): raise ValidationError(("Value '%s' for %s does not match expression '%s'" % (value, key, self.re.pattern))) ...
'Initialize recompilable regex value. Args: attribute: Attribute validator associated with this regex value. value: Initial underlying python value for regex string. Either a single regex string or a list of regex strings. key: Name of the field.'
def __init__(self, attribute, value, key):
self.__attribute = attribute self.__value = value self.__regex = None self.__key = key
'Convert a value to appropriate string. Returns: String version of value with all carriage returns and line feeds removed.'
def __AsString(self, value):
if issubclass(self.__attribute.expected_type, str): cast_value = TYPE_STR(value) else: cast_value = TYPE_UNICODE(value) cast_value = cast_value.replace('\n', '') cast_value = cast_value.replace('\r', '') return cast_value
'Build regex string from state. Returns: String version of regular expression. Sequence objects are constructed as larger regular expression where each regex in the list is joined with all the others as single \'or\' expression.'
def __BuildRegex(self):
if isinstance(self.__value, list): value_list = self.__value sequence = True else: value_list = [self.__value] sequence = False regex_list = [] for item in value_list: regex_list.append(self.__AsString(item)) if sequence: return '|'.join((('(?:%s)' % i...
'Build regular expression object from state. Returns: Compiled regular expression based on internal value.'
def __Compile(self):
regex = self.__BuildRegex() try: return re.compile(regex) except re.error as e: raise ValidationError(("Value '%s' for %s does not compile: %s" % (regex, self.__key, e)), e)
'Compiled regular expression as described by underlying value.'
@property def regex(self):
return self.__Compile()
'Match against internal regular expression. Returns: Regular expression object built from underlying value.'
def match(self, value):
return re.match(self.__BuildRegex(), value)
'Ensure that regex string compiles.'
def Validate(self):
self.__Compile()
'Regular expression string as described by underlying value.'
def __str__(self):
return self.__BuildRegex()
'Comparison against other regular expression string values.'
def __eq__(self, other):
if isinstance(other, _RegexStrValue): return (self.__BuildRegex() == other.__BuildRegex()) return (str(self) == other)
'Inequality operator for regular expression string value.'
def __ne__(self, other):
return (not self.__eq__(other))
'Initialized regex validator. Raises: AttributeDefinitionError if string_type is not a kind of string.'
def __init__(self, string_type=unicode, default=None):
if (default is not None): default = _RegexStrValue(self, default, None) re.compile(str(default)) super(RegexStr, self).__init__(default) if ((not issubclass(string_type, basestring)) or (string_type is basestring)): raise AttributeDefinitionError(('RegexStr fields must be ...
'Validates that the string compiles as a regular expression. Because the regular expression might have been expressed as a multiline string, this function also strips newlines out of value. Args: value: String to compile as a regular expression. key: Name of the field being validated. Raises: ValueError when value does...
def Validate(self, value, key):
if isinstance(value, _RegexStrValue): return value value = _RegexStrValue(self, value, key) value.Validate() return value
'Returns the RE pattern for this validator.'
def ToValue(self, value):
return str(value)
'Initializer for range. Args: minimum: Minimum for attribute. maximum: Maximum for attribute. range_type: Type of field. Defaults to int.'
def __init__(self, minimum, maximum, range_type=int, default=None):
super(Range, self).__init__(default) if (not isinstance(minimum, range_type)): raise AttributeDefinitionError(('Minimum value must be of type %s, instead it is %s (%s).' % (str(range_type), str(type(minimum)), str(minimum)))) if (not isinstance(maximum, range_type)):...
'Validate that value is within range. Validates against range-type then checks the range. Args: value: Value to validate. key: Name of the field being validated. Raises: ValidationError when value is out of range. ValidationError when value is notd of the same range type.'
def Validate(self, value, key):
cast_value = self._type_validator.Validate(value, key) if ((cast_value < self.minimum) or (cast_value > self.maximum)): raise ValidationError(("Value '%s' for %s is out of range %s - %s" % (str(value), key, str(self.minimum), str(self.maximum)))) return cast_value
'Initializer for repeated field. Args: constructor: Type used for verifying elements of sequence attribute.'
def __init__(self, constructor, default=None):
super(Repeated, self).__init__(default) self.constructor = constructor self.expected_type = list
'Do validation of sequence. Value must be a list and all elements must be of type \'constructor\'. Args: value: Value to validate. key: Name of the field being validated. Raises: ValidationError if value is None, not a list or one of its elements is the wrong type.'
def Validate(self, value, key):
if (not isinstance(value, list)): raise ValidationError(("Value '%s' for %s should be a sequence but is not." % (value, key))) for item in value: if isinstance(self.constructor, Validator): item = self.constructor.Validate(item, key) elif (not is...
'Initialize PyYAML event listener. Constructs internal mapping directly from event type to method on actual handler. This prevents reflection being used during actual parse time. Args: event_handler: Event handler that will receive mapped events. Must implement at least one appropriate handler method named from the va...
def __init__(self, event_handler):
if (not isinstance(event_handler, EventHandler)): raise yaml_errors.ListenerConfigurationError('Must provide event handler of type yaml_listener.EventHandler') self._event_method_map = {} for (event, method) in _EVENT_METHOD_MAP.iteritems(): self._event_method_map[event] = ...
'Handle individual PyYAML event. Args: event: Event to forward to method call in method call. Raises: IllegalEvent when receives an unrecognized or unsupported event type.'
def HandleEvent(self, event, loader=None):
if (event.__class__ not in _EVENT_METHOD_MAP): raise yaml_errors.IllegalEvent(('%s is not a valid PyYAML class' % event.__class__.__name__)) if (event.__class__ in self._event_method_map): self._event_method_map[event.__class__](event, loader)
'Iterate over all events and send them to handler. This method is not meant to be called from the interface. Only use in tests. Args: events: Iterator or generator containing events to process. raises: EventListenerParserError when a yaml.parser.ParserError is raised. EventError when an exception occurs during the hand...
def _HandleEvents(self, events):
for event in events: try: self.HandleEvent(*event) except Exception as e: (event_object, loader) = event raise yaml_errors.EventError(e, event_object)
'Creates a generator that yields event, loader parameter pairs. For use as parameters to HandleEvent method for use by Parse method. During testing, _GenerateEventParameters is simulated by allowing the harness to pass in a list of pairs as the parameter. A list of (event, loader) pairs must be passed to _HandleEvents ...
def _GenerateEventParameters(self, stream, loader_class=yaml.loader.SafeLoader):
assert (loader_class is not None) try: loader = loader_class(stream) while loader.check_event(): (yield (loader.get_event(), loader)) except yaml.error.YAMLError as e: raise yaml_errors.EventListenerYAMLError(e)
'Call YAML parser to generate and handle all events. Calls PyYAML parser and sends resulting generator to handle_event method for processing. Args: stream: String document or open file object to process as per the yaml.parse method. Any object that implements a \'read()\' method which returns a string document will wo...
def Parse(self, stream, loader_class=yaml.loader.SafeLoader):
self._HandleEvents(self._GenerateEventParameters(stream, loader_class))
'Constructs a new XMPP Message from an HTTP request. Args: vars: A dict-like object to extract message arguments from.'
def __init__(self, vars):
try: self.__sender = vars['from'] self.__to = vars['to'] self.__body = vars['body'] except KeyError as e: raise InvalidMessageError(e[0]) self.__command = None self.__arg = None
'Convenience function to reply to a message. Args: body: str: The body of the message message_type, raw_xml: As per send_message. send_message: Used for testing. Returns: A status code as per send_message. Raises: See send_message.'
def reply(self, body, message_type=MESSAGE_TYPE_CHAT, raw_xml=False, send_message=send_message):
return send_message([self.sender], body, from_jid=self.to, message_type=message_type, raw_xml=raw_xml)
'Initializer. Args: log: A logger, used for dependency injection. service_name: Service name expected for all calls.'
def __init__(self, log=logging.info, service_name='xmpp'):
super(XmppServiceStub, self).__init__(service_name) self.log = log
'Implementation of XmppService::GetPresence. Returns online if the first character of the JID comes before \'m\' in the alphabet, otherwise returns offline. Args: request: A PresenceRequest. response: A PresenceResponse.'
def _Dynamic_GetPresence(self, request, response):
self._GetFrom(request.from_jid()) self._FillInPresenceResponse(request.jid(), response)
'Arbitrarily fill in a presence response or subresponse.'
def _FillInPresenceResponse(self, jid, response):
response.set_is_available((jid[0] < 'm')) response.set_valid(self._ValidateJid(jid)) response.set_presence(1)
'Implementation of XmppService::SendMessage. Args: request: An XmppMessageRequest. response: An XmppMessageResponse .'
def _Dynamic_SendMessage(self, request, response):
from_jid = self._GetFrom(request.from_jid()) log_message = [] log_message.append('Sending an XMPP Message:') log_message.append(' From:') log_message.append((' ' + from_jid)) log_message.append(' Body:') log_message.append((' ...
'Implementation of XmppService::SendInvite. Args: request: An XmppInviteRequest. response: An XmppInviteResponse .'
def _Dynamic_SendInvite(self, request, response):
from_jid = self._GetFrom(request.from_jid()) self._ParseJid(request.jid()) log_message = [] log_message.append('Sending an XMPP Invite:') log_message.append(' From:') log_message.append((' ' + from_jid)) log_message.append((' ...
'Implementation of XmppService::SendPresence. Args: request: An XmppSendPresenceRequest. response: An XmppSendPresenceResponse .'
def _Dynamic_SendPresence(self, request, response):
from_jid = self._GetFrom(request.from_jid()) log_message = [] log_message.append('Sending an XMPP Presence:') log_message.append(' From:') log_message.append((' ' + from_jid)) log_message.append((' To: ' + request.jid())) i...
'Parse the given JID. Also tests that the given jid: * Contains one and only one @. * Has one or zero resources. * Has a node. * Does not contain any invalid characters. Args: jid: The JID to validate Returns: A tuple (node, domain, resource) representing the JID. Raises: apiproxy_errors.ApplicationError if the request...
def _ParseJid(self, jid):
if set(jid).intersection(INVALID_JID_CHARACTERS): self.log('Invalid JID: characters "%s" not supported. JID: %s', INVALID_JID_CHARACTERS, jid) raise apiproxy_errors.ApplicationError(xmpp_service_pb.XmppServiceError.INVALID_JID) (node, domain, resource) = ('', '', '') ...
'Validate the given JID using self._ParseJid.'
def _ValidateJid(self, jid):
try: self._ParseJid(jid) return True except apiproxy_errors.ApplicationError: return False
'Validates that the from JID is valid. The JID uses the display-app-id for all apps to simulate a common case in production (alias === display-app-id). Args: requested: The requested from JID. Returns: string, The from JID. Raises: apiproxy_errors.ApplicationError if the requested JID is invalid.'
def _GetFrom(self, requested):
full_appid = os.environ.get('APPLICATION_ID') (partition, _, display_app_id) = app_identity.app_identity._ParseFullAppId(full_appid) if ((requested == None) or (requested == '')): return (display_app_id + '@appspot.com/bot') (node, domain, resource) = self._ParseJid(requested) if ((domain ==...
'Implementation of XmppService::CreateChannel. Args: request: A CreateChannelRequest. response: A CreateChannelResponse.'
def _Dynamic_CreateChannel(self, request, response):
log_message = [] log_message.append('Sending a Create Channel:') log_message.append(' Client ID:') log_message.append((' ' + request.application_key())) if request.duration_minutes(): log_message.append((' Duration minut...
'Implementation of XmppService::SendChannelMessage. Args: request: A SendMessageRequest. response: A SendMessageRequest.'
def _Dynamic_SendChannelMessage(self, request, response):
log_message = [] log_message.append('Sending a Channel Message:') log_message.append(' Client ID:') log_message.append((' ' + request.application_key())) log_message.append(' Message:') log_message.append((' ...
'Initializer. Args: log: A logger, used for dependency injection. service_name: Service name expected for all calls.'
def __init__(self, log=logging.info, service_name='xmpp', domain='localhost', uaserver='localhost', uasecret=''):
super(XmppService, self).__init__(service_name) self.log = log self.xmpp_domain = domain self.uaserver = ('https://' + uaserver) self.login = 'https://localhost:17443' if (not uasecret): if os.path.exists(SECRET_KEY_FILE): secret_file = open(SECRET_KEY_FILE, 'r') ...
'Implementation of XmppService::GetPresence. Reads the file containing the list of online users to see if the given user is online or not. Args: request: A PresenceRequest. response: A PresenceResponse.'
def _Dynamic_GetPresence(self, request, response):
jid = request.jid() server = SOAPpy.SOAPProxy(self.login) online_users = server.get_online_users_list(self.uasecret) user_is_online = False try: online_users.index(jid) user_is_online = True except ValueError: pass response.set_is_available(user_is_online)
'Implementation of XmppService::SendMessage. Args: request: An XmppMessageRequest. response: An XmppMessageResponse .'
def _Dynamic_SendMessage(self, request, response):
appname = os.environ['APPNAME'] xmpp_username = ((appname + '@') + self.xmpp_domain) my_jid = xmpppy.protocol.JID(xmpp_username) client = xmpppy.Client(my_jid.getDomain(), debug=[]) client.connect(secure=False) client.auth(my_jid.getNode(), self.uasecret, resource=my_jid.getResource()) for j...
'Implementation of XmppService::SendInvite. Args: request: An XmppInviteRequest. response: An XmppInviteResponse .'
def _Dynamic_SendInvite(self, request, response):
pass
'Validates that the from JID is valid. Args: requested: The requested from JID. Returns: string, The from JID. Raises: xmpp.InvalidJidError if the requested JID is invalid.'
def _GetFrom(self, requested):
appid = os.environ.get('APPLICATION_ID', '') if ((requested == None) or (requested == '')): return (((appid + '@') + self.xmpp_domain) + '/bot') (node, domain, resource) = ('', '', '') at = requested.find('@') if (at == (-1)): self.log("Invalid From JID: No '@' charact...
'Implementation of channel.get_channel. Args: request: A ChannelServiceRequest. response: A ChannelServiceResponse'
def _Dynamic_CreateChannel(self, request, response):
application_key = request.application_key() if (not application_key): raise apiproxy_errors.ApplicationError(channel_service_pb.ChannelServiceError.INVALID_CHANNEL_KEY) application_key = urllib.quote(application_key) if ('@' in application_key): raise apiproxy_errors.ApplicationError(cha...