desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Constructor. Args: filename: the name of the file to read as string. buffer_size: buffer read size to use as int.'
def __init__(self, filename, buffer_size=_DEFAULT_BUFFER_SIZE):
self._filename = filename self._position = 0 self._buffer = '' self._buffer_pos = 0 self._buffer_size = buffer_size self._eof = False
'Return file\'s current position.'
def tell(self):
return self._position
'Read data from RAW file. Args: size: Number of bytes to read as integer. Actual number of bytes read is always equal to size unless end if file was reached. Returns: A string with data read.'
def read(self, size):
data_list = [] while True: result = self.__readBuffer(size) data_list.append(result) size -= len(result) if ((size == 0) or self._eof): return ''.join(data_list) self.__refillBuffer()
'Read one line delimited by \' \' from the file. A trailing newline character is kept in the string. It may be absent when a file ends with an incomplete line. If the size argument is non-negative, it specifies the maximum string size (counting the newline) to return. An empty string is returned only when EOF is encoun...
def readline(self, size=(-1)):
data_list = [] while True: if (size < 0): end_pos = len(self._buffer) else: end_pos = (self._buffer_pos + size) newline_pos = self._buffer.find('\n', self._buffer_pos, end_pos) if (newline_pos != (-1)): data_list.append(self.__readBuffer(((newl...
'Read chars from self._buffer. Args: size: number of chars to read. Read the entire buffer if negative. Returns: chars read in string.'
def __readBuffer(self, size):
if (size < 0): size = (len(self._buffer) - self._buffer_pos) result = self._buffer[self._buffer_pos:(self._buffer_pos + size)] self._position += len(result) self._buffer_pos += len(result) return result
'Refill _buffer with another read from source.'
def __refillBuffer(self):
with open(self._filename, 'r') as f: f.seek(self._position) data = f.read(self._buffer_size) self._eof = (len(data) < self._buffer_size) self._buffer = data self._buffer_pos = 0
'Set the file\'s current position. Args: offset: seek offset as number. whence: seek mode. Supported modes are os.SEEK_SET (absolute seek), os.SEEK_CUR (seek relative to the current position), and os.SEEK_END (seek relative to the end, offset should be negative).'
def seek(self, offset, whence=os.SEEK_SET):
if (whence == os.SEEK_SET): self._position = offset self._buffer = '' self._buffer_pos = 0 elif (whence == os.SEEK_CUR): self._position += offset self._buffer = '' self._buffer_pos = 0 elif (whence == os.SEEK_END): file_stat = stat(self._filename) ...
'Get current in-memory file content.'
def get_content(self, filename):
return self._file_content.get(filename, '')
'Set current in-memory file content.'
def set_content(self, filename, content):
self._file_content[filename] = content
'Constructor.'
def __init__(self):
self.__content = [] self.__unique_keys = set()
'Returns the amount of elements in the collection.'
def __len__(self):
return self.__content.__len__()
'Appends a hook at a certain position in the list. Args: index: the index of where to insert the function key: a unique key (within the module) for this particular function. If something from the same module with the same key is already registered, nothing will be added. function: the hook to be added. service: optiona...
def __Insert(self, index, key, function, service=None):
unique_key = (key, inspect.getmodule(function)) if (unique_key in self.__unique_keys): return False num_args = len(inspect.getargspec(function)[0]) if inspect.ismethod(function): num_args -= 1 self.__content.insert(index, (key, function, service, num_args)) self.__unique_keys.add...
'Appends a hook at the end of the list. Args: key: a unique key (within the module) for this particular function. If something from the same module with the same key is already registered, nothing will be added. function: the hook to be added. service: optional argument that restricts the hook to a particular api Retur...
def Append(self, key, function, service=None):
return self.__Insert(len(self), key, function, service)
'Inserts a hook at the beginning of the list. Args: key: a unique key (within the module) for this particular function. If something from the same module with the same key is already registered, nothing will be added. function: the hook to be added. service: optional argument that restricts the hook to a particular api...
def Push(self, key, function, service=None):
return self.__Insert(0, key, function, service)
'Removes all hooks from the list (useful for unit tests).'
def Clear(self):
self.__content = [] self.__unique_keys = set()
'Invokes all hooks in this collection. NOTE: For backwards compatibility, if error is not None, hooks with 4 or 5 arguments are *not* called. This situation (error=None) only occurs when the RPC request raised an exception; in the past no hooks would be called at all in that case. Args: service: string representing wh...
def Call(self, service, call, request, response, rpc=None, error=None):
for (key, function, srv, num_args) in self.__content: if ((srv is None) or (srv == service)): if (num_args == 6): function(service, call, request, response, rpc, error) elif (error is not None): pass elif (num_args == 5): fu...
'Constructor. Args: default_stub: optional stub \'default_stub\' will be used whenever no specific matching stub is found.'
def __init__(self, default_stub=None):
self.__stub_map = {} self.__default_stub = default_stub self.__precall_hooks = ListOfHooks() self.__postcall_hooks = ListOfHooks()
'Gets a collection for all precall hooks.'
def GetPreCallHooks(self):
return self.__precall_hooks
'Gets a collection for all precall hooks.'
def GetPostCallHooks(self):
return self.__postcall_hooks
'Replace the existing stub for the specified service with a new one. NOTE: This is a risky operation; external callers should use this with caution. Args: service: string stub: stub'
def ReplaceStub(self, service, stub):
self.__stub_map[service] = stub if (service == 'datastore'): self.RegisterStub('datastore_v3', stub)
'Register the provided stub for the specified service. Args: service: string stub: stub'
def RegisterStub(self, service, stub):
self.ReplaceStub(service, stub)
'Retrieve the stub registered for the specified service. Args: service: string Returns: stub Returns the stub registered for \'service\', and returns the default stub if no such stub is found.'
def GetStub(self, service):
return self.__stub_map.get(service, self.__default_stub)
'The APIProxy entry point. Args: service: string representing which service to call call: string representing which function to call request: protocol buffer for the request response: protocol buffer for the response Returns: Response protocol buffer or None. Some implementations may return a response protocol buffer i...
def MakeSyncCall(self, service, call, request, response):
stub = self.GetStub(service) assert stub, ('No api proxy found for service "%s"' % service) if hasattr(stub, 'CreateRPC'): rpc = stub.CreateRPC() self.__precall_hooks.Call(service, call, request, response, rpc) try: rpc.MakeCall(service, call, request, r...
'Constructor. Args: service: The service name. deadline: Optional deadline. Default depends on the implementation. callback: Optional argument-less callback function. stubmap: optional APIProxyStubMap instance, for dependency injection.'
def __init__(self, service, deadline=None, callback=None, stubmap=None):
if (stubmap is None): stubmap = apiproxy self.__stubmap = stubmap self.__service = service self.__rpc = CreateRPC(service, stubmap) self.__rpc.deadline = deadline self.__rpc.callback = self.__internal_callback self.callback = callback self.__class__.__local.may_interrupt_wait = F...
'This is the callback set on the low-level RPC object. It sets a flag on the current object indicating that the high-level callback should now be called. If interrupts are enabled, it also interrupts the current wait_any() call by raising an exception.'
def __internal_callback(self):
self.__must_call_user_callback = True self.__rpc.callback = None if (self.__class__.__local.may_interrupt_wait and (not self.__rpc.exception)): pass
'Return the service name.'
@property def service(self):
return self.__service
'Return the method name.'
@property def method(self):
return self.__method
'Return the deadline, if set explicitly (otherwise None).'
@property def deadline(self):
return self.__rpc.deadline
'Return the request protocol buffer object.'
@property def request(self):
return self.__rpc.request
'Return the response protocol buffer object.'
@property def response(self):
return self.__rpc.response
'Return the RPC state. Possible values are attributes of apiproxy_rpc.RPC: IDLE, RUNNING, FINISHING.'
@property def state(self):
return self.__rpc.state
'Return the get-result hook function.'
@property def get_result_hook(self):
return self.__get_result_hook
'Return the user data for the hook function.'
@property def user_data(self):
return self.__user_data
'Initiate a call. Args: method: The method name. request: The request protocol buffer. response: The response protocol buffer. get_result_hook: Optional get-result hook function. If not None, this must be a function with exactly one argument, the RPC object (self). Its return value is returned from get_result(). user...
def make_call(self, method, request, response, get_result_hook=None, user_data=None):
assert (self.__rpc.state == apiproxy_rpc.RPC.IDLE), repr(self.state) self.__method = method self.__get_result_hook = get_result_hook self.__user_data = user_data self.__stubmap.GetPreCallHooks().Call(self.__service, method, request, response, self.__rpc) self.__rpc.MakeCall(self.__service, metho...
'Wait for the call to complete, and call callback if needed. This and wait_any()/wait_all() are the only time callback functions may be called. (However, note that check_success() and get_result() call wait().) Waiting for one RPC will not cause callbacks for other RPCs to be called. Callback functions may call chec...
def wait(self):
assert (self.__rpc.state != apiproxy_rpc.RPC.IDLE), repr(self.state) if (self.__rpc.state == apiproxy_rpc.RPC.RUNNING): self.__rpc.Wait() assert (self.__rpc.state == apiproxy_rpc.RPC.FINISHING), repr(self.state) self.__call_user_callback()
'Call the high-level callback, if requested.'
def __call_user_callback(self):
if self.__must_call_user_callback: self.__must_call_user_callback = False if (self.callback is not None): self.callback()
'Check for success of the RPC, possibly raising an exception. This function should be called at least once per RPC. If wait() hasn\'t been called yet, it is called first. If the RPC caused an exceptional condition, an exception will be raised here. The first time check_success() is called, the postcall hooks are call...
def check_success(self):
self.wait() try: self.__rpc.CheckSuccess() except Exception as err: if (not self.__postcall_hooks_called): self.__postcall_hooks_called = True self.__stubmap.GetPostCallHooks().Call(self.__service, self.__method, self.request, self.response, self.__rpc, err) r...
'Get the result of the RPC, or possibly raise an exception. This implies a call to check_success(). If a get-result hook was passed to make_call(), that hook is responsible for calling check_success(), and the return value of the hook is returned. Otherwise, check_success() is called directly and None is returned.'
def get_result(self):
if (self.__get_result_hook is None): self.check_success() return None else: return self.__get_result_hook(self)
'Check the list of RPCs for one that is finished, or one that is running. Args: rpcs: Iterable collection of UserRPC instances. Returns: A pair (finished, running), as follows: (UserRPC, None) indicating the first RPC found that is finished; (None, UserRPC) indicating the first RPC found that is running; (None, None) i...
@classmethod def __check_one(cls, rpcs):
rpc = None for rpc in rpcs: assert isinstance(rpc, cls), repr(rpc) state = rpc.__rpc.state if (state == apiproxy_rpc.RPC.FINISHING): rpc.__call_user_callback() return (rpc, None) assert (state != apiproxy_rpc.RPC.IDLE), repr(rpc) return (None, rpc)
'Wait until an RPC is finished. Args: rpcs: Iterable collection of UserRPC instances. Returns: A UserRPC instance, indicating the first RPC among the given RPCs that finished; or None, indicating that either an RPC not among the given RPCs finished in the mean time, or the iterable is empty. NOTES: (1) Repeatedly calli...
@classmethod def wait_any(cls, rpcs):
assert (iter(rpcs) is not rpcs), 'rpcs must be a collection, not an iterator' (finished, running) = cls.__check_one(rpcs) if (finished is not None): return finished if (running is None): return None try: cls.__local.may_interrupt_wait = True try: ...
'Wait until all given RPCs are finished. This is a thin wrapper around wait_any() that loops until all given RPCs have finished. Args: rpcs: Iterable collection of UserRPC instances. Returns: None.'
@classmethod def wait_all(cls, rpcs):
rpcs = set(rpcs) while rpcs: finished = cls.wait_any(rpcs) if (finished is not None): rpcs.remove(finished)
'Override the kind name to prevent collisions with users.'
@classmethod def kind(cls):
return CONFIG_KIND
'Loads all the params from a YAMLConfiguration into expando fields. We set these expando properties with a special name prefix \'p_\' to keep them separate from the static attributes of Config. That way we don\'t have to check elsewhere to make sure the user doesn\'t stomp on our built in properties. Args: parse_confi...
def ah__conf__load_from_yaml(self, parsed_config):
for (key, value) in parsed_config.parameters.iteritems(): setattr(self, key, value)
'Check that all parameter names are valid. This is used as a validator when parsing conf.yaml. Args: value: the value to check. key: A description of the context for which this value is being validated. Returns: The validated value.'
def Validate(self, value, key):
value = self.regex.Validate(value, key) try: db.check_reserved_word(value) except db.ReservedWordError: raise validation.ValidationError(('The config parameter name %.100r is reserved by db.Model see: https://developers.google.com/appengine/docs/python/datastore...
'Check that all parameters are scalar values. This is used as a validator when parsing conf.yaml Args: value: the value to check. key: the name of parameter corresponding to this value. Returns: We just return value unchanged.'
def Validate(self, value, key):
if (type(value) not in self.ALLOWED_PARAMETER_VALUE_TYPES): raise validation.ValidationError(('Expected scalar value for parameter: %s, but found %.100r which is type %s' % (key, value, type(value).__name__))) return value
'Constructor for the RPC object. All arguments are optional, and simply set members on the class. These data members will be overriden by values passed to MakeCall. Args: package: string, the package for the call call: string, the call within the package request: ProtocolMessage instance, appropriate for the arguments ...
def __init__(self, package=None, call=None, request=None, response=None, callback=None, deadline=None, stub=None):
self._exception = None self._state = RPC.IDLE self._traceback = None self.package = package self.call = call self.request = request self.response = response self.callback = callback self.deadline = deadline self.stub = stub
'Make a shallow copy of this instances attributes, excluding methods. This is usually used when an RPC has been specified with some configuration options and is being used as a template for multiple RPCs outside of a developer\'s easy control.'
def Clone(self):
if (self._state != RPC.IDLE): raise AssertionError('Cannot clone a call already in progress') clone = self.__class__() for (k, v) in self.__dict__.iteritems(): setattr(clone, k, v) return clone
'Makes an asynchronous (i.e. non-blocking) API call within the specified package for the specified call method. It will call the _MakeRealCall to do the real job. Args: Same as constructor; see __init__. Raises: TypeError or AssertionError if an argument is of an invalid type. AssertionError or RuntimeError is an RPC i...
def MakeCall(self, package=None, call=None, request=None, response=None, callback=None, deadline=None):
self.callback = (callback or self.callback) self.package = (package or self.package) self.call = (call or self.call) self.request = (request or self.request) self.response = (response or self.response) self.deadline = (deadline or self.deadline) assert (self._state is RPC.IDLE), ('RPC for...
'Waits on the API call associated with this RPC.'
def Wait(self):
rpc_completed = self._WaitImpl() assert rpc_completed, ('RPC for %s.%s was not completed, and no other exception was raised ' % (self.package, self.call))
'If there was an exception, raise it now. Raises: Exception of the API call or the callback, if any.'
def CheckSuccess(self):
if (self._exception and self._traceback): raise self._exception.__class__, self._exception, self._traceback elif self._exception: raise self._exception
'Override this method to implement a real asynchronous call rpc.'
def _MakeCallImpl(self):
self._state = RPC.RUNNING
'Override this method to implement a real asynchronous call rpc. Returns: True if the async call was completed successfully.'
def _WaitImpl(self):
try: self.stub.MakeSyncCall(self.package, self.call, self.request, self.response) except Exception: (_, self._exception, self._traceback) = sys.exc_info() finally: self._state = RPC.FINISHING self._Callback() return True
'Create a RealRPC instance. Args: stub: A stub instance that handles the actual call.'
def __init__(self, stub=None):
super(RealRPC, self).__init__(stub=stub) self._exc_info = None self._exc_info_lock = threading.Lock()
'Starts the thread which calls upon the service RPC.'
def _MakeCallImpl(self):
args = [self.package, self.call, self.request, self.response] if hasattr(self.stub, '_GetRequestId'): args.extend([self.stub._GetRequestId(), os.environ.copy()]) self._thread = threading.Thread(target=self._make_sync_call, args=args) self._thread.start() self._state = RPC.RUNNING
'Waiting on an RPC call thread to complete'
def _WaitImpl(self):
self._thread.join() with self._exc_info_lock: if (self._exc_info is not None): (_, self._exception, self._traceback) = self._exc_info self._state = RPC.FINISHING self._Callback() return True
'A wrapper for MakeSyncCall that handles exceptions. Args: service: A string the specifies the API service. call: A string specifying the service method to call. request: A ProtocolMessage instance that specifies request properties. response: A ProtocolMessage instance that the response populates. request_id: A string ...
def _make_sync_call(self, service, call, request, response, request_id=None, os_environ=None):
if ((request_id is not None) and hasattr(self.stub, '_SetRequestId')): self.stub._SetRequestId(request_id) if (os_environ is not None): os.environ.update(os_environ) try: self.stub.MakeSyncCall(service, call, request, response) except Exception: with self._exc_info_lock: ...
'Initializer. Args: min_backoff_seconds: The minimum number of seconds to wait before retrying a task after failure. (optional) max_backoff_seconds: The maximum number of seconds to wait before retrying a task after failure. (optional) task_age_limit: The number of seconds after creation afterwhich a failed task will n...
def __init__(self, **kwargs):
args_diff = (set(kwargs.iterkeys()) - self.__CONSTRUCTOR_KWARGS) if args_diff: raise TypeError(('Invalid arguments: %s' % ', '.join(args_diff))) self.__min_backoff_seconds = kwargs.get('min_backoff_seconds') if ((self.__min_backoff_seconds is not None) and (self.__min_backoff_seconds < ...
'The minimum number of seconds to wait before retrying a task.'
@property def min_backoff_seconds(self):
return self.__min_backoff_seconds
'The maximum number of seconds to wait before retrying a task.'
@property def max_backoff_seconds(self):
return self.__max_backoff_seconds
'The number of seconds afterwhich a failed task will not be retried.'
@property def task_age_limit(self):
return self.__task_age_limit
'The number of times that the retry interval will be doubled.'
@property def max_doublings(self):
return self.__max_doublings
'The number of times that a failed task will be retried.'
@property def task_retry_limit(self):
return self.__task_retry_limit
'Initializer. All parameters are optional. Args: payload: The payload data for this Task that will be delivered to the webhook as the HTTP request body. This is only allowed for POST and PUT methods. countdown: Time in seconds into the future that this Task should execute. Defaults to zero. eta: Absolute time when the ...
def __init__(self, payload=None, **kwargs):
args_diff = (set(kwargs.iterkeys()) - self.__CONSTRUCTOR_KWARGS) if args_diff: raise TypeError(('Invalid arguments: %s' % ', '.join(args_diff))) self.__name = kwargs.get('name') if (self.__name and (not _TASK_NAME_RE.match(self.__name))): raise InvalidTaskNameError(('Task nam...
'Determines the URL of a task given a relative URL and a name. Args: relative_url: The relative URL for the Task. Returns: Tuple (default_url, relative_url, query) where: default_url: True if this Task is using the default URL scheme; False otherwise. relative_url: String containing the relative URL for this Task. quer...
@staticmethod def __determine_url(relative_url):
if (not relative_url): (default_url, query) = (True, '') else: default_url = False try: (relative_url, query) = _parse_relative_url(relative_url) except _RelativeUrlError as e: raise InvalidUrlError(e) if (len(relative_url) > MAX_URL_LENGTH): r...
'Determines the ETA for a task. If \'eta\' and \'countdown\' are both None, the current time will be used. Otherwise, only one of them may be specified. Args: eta: A datetime.datetime specifying the absolute ETA or None; this may be timezone-aware or timezone-naive. countdown: Count in seconds into the future from the ...
@staticmethod def __determine_eta_posix(eta=None, countdown=None, current_time=time.time):
if ((eta is not None) and (countdown is not None)): raise InvalidTaskError('May not use a countdown and ETA together') elif (eta is not None): if (not isinstance(eta, datetime.datetime)): raise InvalidTaskError('ETA must be a datetime.datetime inst...
'URL-encodes a list of parameters. Args: params: Dictionary of parameters, possibly with iterable values. Returns: URL-encoded version of the params, ready to be added to a query string or POST body.'
@staticmethod def __encode_params(params):
return urllib.urlencode(_flatten_params(params))
'Converts a Task payload into UTF-8 and sets headers if necessary. Args: payload: The payload data to convert. headers: Dictionary of headers. Returns: The payload as a non-unicode string. Raises: InvalidTaskError if the payload is not a string or unicode instance.'
@staticmethod def __convert_payload(payload, headers):
if isinstance(payload, unicode): headers.setdefault('content-type', 'text/plain; charset=utf-8') payload = payload.encode('utf-8') elif (not isinstance(payload, str)): raise InvalidTaskError(('Task payloads must be strings; invalid payload: %r' % payload)) ret...
'Returns True if this Task will run on the queue\'s URL.'
@property def on_queue_url(self):
return self.__default_url
'Returns a POSIX timestamp giving when this Task will execute.'
@property def eta_posix(self):
if ((self.__eta_posix is None) and (self.__eta is not None)): self.__eta_posix = Task.__determine_eta_posix(self.__eta) return self.__eta_posix
'Returns a datetime when this Task will execute.'
@property def eta(self):
if ((self.__eta is None) and (self.__eta_posix is not None)): self.__eta = datetime.datetime.fromtimestamp(self.__eta_posix, _UTC) return self.__eta
'Returns a copy of the headers for this Task.'
@property def headers(self):
return self.__headers.copy()
'Returns the method to use for this Task.'
@property def method(self):
return self.__method
'Returns the name of this Task. Will be None if using auto-assigned Task names and this Task has not yet been added to a Queue.'
@property def name(self):
return self.__name
'Returns the payload for this task, which may be None.'
@property def payload(self):
return self.__payload
'Returns the size of this task in bytes.'
@property def size(self):
HEADER_SEPERATOR = len(': \r\n') header_size = sum((((len(key) + len(value)) + HEADER_SEPERATOR) for (key, value) in self.__headers_list)) return (((len(self.__method) + len((self.__payload or ''))) + len(self.__relative_url)) + header_size)
'Returns the relative URL for this Task.'
@property def url(self):
return self.__relative_url
'Returns the TaskRetryOptions for this task, which may be None.'
@property def retry_options(self):
return self.__retry_options
'Returns True if this Task has been enqueued. Note: This will not check if this task already exists in the queue.'
@property def was_enqueued(self):
return self.__enqueued
'Adds this Task to a queue. See Queue.add.'
def add(self, queue_name=_DEFAULT_QUEUE, transactional=False):
return Queue(queue_name).add(self, transactional=transactional)
'Initializer. Args: name: Name of this queue. If not supplied, defaults to the default queue. Raises: InvalidQueueNameError if the queue name is invalid.'
def __init__(self, name=_DEFAULT_QUEUE):
if (not _QUEUE_NAME_RE.match(name)): raise InvalidQueueNameError(('Queue name does not match pattern "%s"; found %s' % (_QUEUE_NAME_PATTERN, name))) self.__name = name self.__url = ('%s/%s' % (_DEFAULT_QUEUE_PATH, self.__name)) self._app = None
'Removes all the tasks in this Queue. This function takes constant time to purge a Queue and some delay may apply before the call is effective. Raises: UnknownQueueError if the Queue does not exist on server side.'
def purge(self):
request = taskqueue_service_pb.TaskQueuePurgeQueueRequest() response = taskqueue_service_pb.TaskQueuePurgeQueueResponse() request.set_queue_name(self.__name) if self._app: request.set_app_id(self._app) try: apiproxy_stub_map.MakeSyncCall('taskqueue', 'PurgeQueue', request, response) ...
'Adds a Task or list of Tasks to this Queue. If a list of more than one Tasks is given, a raised exception does not guarantee that no tasks were added to the queue (unless transactional is set to True). To determine which tasks were successfully added when an exception is raised, check the Task.was_enqueued property. A...
def add(self, task, transactional=False):
try: tasks = list(iter(task)) except TypeError: tasks = [task] multiple = False else: multiple = True self.__AddTasks(tasks, transactional) if multiple: return tasks else: assert (len(tasks) == 1) return tasks[0]
'Internal implementation of .add() where tasks must be a list.'
def __AddTasks(self, tasks, transactional):
if (len(tasks) > MAX_TASKS_PER_ADD): raise TooManyTasksError(('No more than %d tasks can be added in a single add call' % MAX_TASKS_PER_ADD)) request = taskqueue_service_pb.TaskQueueBulkAddRequest() response = taskqueue_service_pb.TaskQueueBulkAddResponse() ta...
'Populates a TaskQueueRetryParameters with data from a TaskRetryOptions. Args: retry_options: The TaskRetryOptions instance to use as a source for the data to be added to retry_retry_parameters. retry_retry_parameters: A taskqueue_service_pb.TaskQueueRetryParameters to populate.'
def __FillTaskQueueRetryParameters(self, retry_options, retry_retry_parameters):
if (retry_options.min_backoff_seconds is not None): retry_retry_parameters.set_min_backoff_sec(retry_options.min_backoff_seconds) if (retry_options.max_backoff_seconds is not None): retry_retry_parameters.set_max_backoff_sec(retry_options.max_backoff_seconds) if (retry_options.task_retry_lim...
'Populates a TaskQueueAddRequest with the data from a Task instance. Args: task: The Task instance to use as a source for the data to be added to task_request. task_request: The taskqueue_service_pb.TaskQueueAddRequest to populate. transactional: If true then populates the task_request.transaction message with informat...
def __FillAddRequest(self, task, task_request, transactional):
if task.was_enqueued: raise BadTaskStateError('Task has already been enqueued') adjusted_url = task.url if task.on_queue_url: adjusted_url = (self.__url + task.url) task_request.set_queue_name(self.__name) task_request.set_eta_usec(long((task.eta_posix * 1000000.0))) ...
'Returns the name of this queue.'
@property def name(self):
return self.__name
'Translates a TaskQueueServiceError into an exception. Args: error: Value from TaskQueueServiceError enum. detail: A human-readable description of the error. Returns: The corresponding Exception sub-class for that error code.'
@staticmethod def __TranslateError(error, detail=''):
if ((error >= taskqueue_service_pb.TaskQueueServiceError.DATASTORE_ERROR) and isinstance(error, int)): from google.appengine.api import datastore datastore_exception = datastore._DatastoreExceptionFromErrorCodeAndDetail((error - taskqueue_service_pb.TaskQueueServiceError.DATASTORE_ERROR), detail) ...
'Constructor.'
def __init__(self):
self._sorted_by_name = [] self._sorted_by_eta = []
'Insert a task into the dummy store, keeps lists sorted. Args: task: the new task.'
def _InsertTask(self, task):
eta = task.eta_usec() name = task.task_name() bisect.insort_left(self._sorted_by_eta, (eta, name, task)) bisect.insort_left(self._sorted_by_name, (name, task))
'Lookup a number of sorted tasks from the store. If \'eta\' is specified, the tasks are looked up in a list sorted by \'eta\', then \'name\'. Otherwise they are sorted by \'name\'. We need to be able to sort by \'eta\' and \'name\' because tasks can have identical eta. If you had 20 tasks with the same ETA, you wouldn\...
def Lookup(self, maximum, name=None, eta=None):
if (eta is None): pos = bisect.bisect_left(self._sorted_by_name, (name,)) tasks = (x[1] for x in self._sorted_by_name[pos:(pos + maximum)]) return list(tasks) if (name is None): raise ValueError('must supply name or eta') pos = bisect.bisect_left(self._sorted_by_e...
'Returns the number of tasks in the store.'
def Count(self):
return len(self._sorted_by_name)
'Returns the oldest eta in the store, or None if no tasks.'
def Oldest(self):
if self._sorted_by_eta: return self._sorted_by_eta[0][0] return None
'Inserts a new task into the store. Args: request: A taskqueue_service_pb.TaskQueueAddRequest. Raises: apiproxy_errors.ApplicationError: If a task with the same name is already in the store.'
def Add(self, request):
pos = bisect.bisect_left(self._sorted_by_name, (request.task_name(),)) if ((pos < len(self._sorted_by_name)) and (self._sorted_by_name[pos][0] == request.task_name())): raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.TASK_ALREADY_EXISTS) now = datetime.datetime.utcn...
'Deletes a task from the store by name. Args: name: the name of the task to delete. Returns: TaskQueueServiceError.UNKNOWN_TASK: if the task is unknown. TaskQueueServiceError.INTERNAL_ERROR: if the store is corrupted. TaskQueueServiceError.OK: otherwise.'
def Delete(self, name):
pos = bisect.bisect_left(self._sorted_by_name, (name,)) if (pos >= len(self._sorted_by_name)): return taskqueue_service_pb.TaskQueueServiceError.UNKNOWN_TASK if (self._sorted_by_name[pos][1].task_name() != name): logging.info('looking for task name %s, got task name %...
'Populates the store with a number of tasks. Args: num_tasks: the number of tasks to insert.'
def Populate(self, num_tasks):
now = datetime.datetime.utcnow() now_sec = time.mktime(now.timetuple()) def RandomTask(): 'Creates a new task and randomly populates values.' task = taskqueue_service_pb.TaskQueueQueryTasksResponse_Task() task.set_task_name(''.join((random.choice(string.ascii_low...
'Constructor. Args: service_name: Service name expected for all calls. root_path: Root path to the directory of the application which may contain a queue.yaml file. If None, then it\'s assumed no queue.yaml file is available. auto_task_running: When True, the dev_appserver should automatically run tasks after they are ...
def __init__(self, service_name='taskqueue', root_path=None, auto_task_running=False, task_retry_seconds=30, _all_queues_valid=False):
super(TaskQueueServiceStub, self).__init__(service_name) self._taskqueues = {} self._next_task_id = 1 self._root_path = root_path self._all_queues_valid = _all_queues_valid self._add_event = None self._auto_task_running = auto_task_running self._task_retry_seconds = task_retry_seconds ...
'Returns a string containing a unique task name.'
def _ChooseTaskName(self):
self._next_task_id += 1 return ('task%d' % (self._next_task_id - 1))
'Checks that a TaskQueueAddRequest is valid. Checks that a TaskQueueAddRequest specifies a valid eta and a valid queue. Args: request: The taskqueue_service_pb.TaskQueueAddRequest to validate. Returns: A taskqueue_service_pb.TaskQueueServiceError indicating any problems with the request or taskqueue_service_pb.TaskQueu...
def _VerifyTaskQueueAddRequest(self, request):
if (request.eta_usec() < 0): return taskqueue_service_pb.TaskQueueServiceError.INVALID_ETA eta = datetime.datetime.utcfromtimestamp((request.eta_usec() / 1000000.0)) max_eta = (datetime.datetime.utcnow() + datetime.timedelta(days=MAX_ETA_DELTA_DAYS)) if (eta > max_eta): return taskqueue_...
'Add many tasks to a queue using a single request. Args: request: The taskqueue_service_pb.TaskQueueBulkAddRequest. See taskqueue_service.proto. response: The taskqueue_service_pb.TaskQueueBulkAddResponse. See taskqueue_service.proto.'
def _Dynamic_BulkAdd(self, request, response):
assert request.add_request_size(), 'taskqueue should prevent empty requests' app_id = None if request.add_request(0).has_app_id(): app_id = request.add_request(0).app_id() if (not self._IsValidQueue(request.add_request(0).queue_name(), app_id)): raise apiproxy_errors.Applicat...
'Uses datastore.AddActions to associate tasks with a transaction. Args: request: The taskqueue_service_pb.TaskQueueBulkAddRequest containing the tasks to add. N.B. all tasks in the request have been validated and assigned unique names.'
def _TransactionalBulkAdd(self, request):
try: apiproxy_stub_map.MakeSyncCall('datastore_v3', 'AddActions', request, api_base_pb.VoidProto()) except apiproxy_errors.ApplicationError as e: raise apiproxy_errors.ApplicationError((e.application_error + taskqueue_service_pb.TaskQueueServiceError.DATASTORE_ERROR), e.error_detail)