desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Sets default auth domain if not set.'
| def _maybeSetDefaultAuthDomain(self):
| auth_domain = os.environ.get('AUTH_DOMAIN')
if (not auth_domain):
os.environ['AUTH_DOMAIN'] = 'appscale.com'
|
'Sends a request remotely to the datstore server.'
| def _RemoteSend(self, request, response, method, request_id=None):
| tag = self.__app_id
self._maybeSetDefaultAuthDomain()
user = users.GetCurrentUser()
if (user != None):
tag += (':' + user.email())
tag += (':' + user.nickname())
tag += (':' + user.auth_domain())
api_request = remote_api_pb.Request()
api_request.set_method(method)
api... |
'Send a put request to the datastore server.'
| def _Dynamic_Put(self, put_request, put_response, request_id=None):
| put_request.set_trusted(self.__trusted)
ent_kinds = []
for ent in put_request.entity_list():
last_path = ent.key().path().element_list()[(-1)]
if (last_path.type() not in ent_kinds):
ent_kinds.append(last_path.type())
for kind in ent_kinds:
indexes = self.__index_cach... |
'Send a get request to the datastore server.'
| def _Dynamic_Get(self, get_request, get_response, request_id=None):
| self._RemoteSend(get_request, get_response, 'Get', request_id)
return get_response
|
'Send a delete request to the datastore server.
Args:
delete_request: datastore_pb.DeleteRequest.
delete_response: datastore_pb.DeleteResponse.
request_id: A string specifying the request ID.
Returns:
A datastore_pb.DeleteResponse from the AppScale datastore server.'
| def _Dynamic_Delete(self, delete_request, delete_response, request_id=None):
| ent_kinds = []
for key in delete_request.key_list():
last_path = key.path().element_list()[(-1)]
if (last_path.type() not in ent_kinds):
ent_kinds.append(last_path.type())
has_composites = False
for kind in ent_kinds:
indexes = self.__index_cache.get(kind)
if ... |
'Send a query request to the datastore server.'
| def _Dynamic_RunQuery(self, query, query_result, request_id=None):
| if query.has_transaction():
if (not query.has_ancestor()):
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST, 'Only ancestor queries are allowed inside transactions.')
(filters, orders) = datastore_index.Normalize(query.filter_list(), query.order_list(),... |
'Get the next set of entities from a previously run query.'
| def _Dynamic_Next(self, next_request, query_result, request_id=None):
| self.__ValidateAppId(next_request.cursor().app())
cursor_handle = next_request.cursor().cursor()
if (cursor_handle not in self.__queries):
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST, ('Cursor %d not found' % cursor_handle))
internal_cursor = self.__queries.get... |
'Get the number of entities for a query.'
| def _Dynamic_Count(self, query, integer64proto, request_id=None):
| query_result = datastore_pb.QueryResult()
self._Dynamic_RunQuery(query, query_result, request_id)
count = query_result.result_size()
integer64proto.set_value(count)
|
'Send a begin transaction request from the datastore server.'
| def _Dynamic_BeginTransaction(self, request, transaction, request_id=None):
| request.set_app(self.__app_id)
self._RemoteSend(request, transaction, 'BeginTransaction', request_id)
self.__tx_actions[transaction.handle()] = []
return transaction
|
'Associates the creation of one or more tasks with a transaction.
Args:
request: A taskqueue_service_pb.TaskQueueBulkAddRequest containing the
tasks that should be created when the transaction is comitted.
response: A taskqueue_service_pb.TaskQueueBulkAddResponse.
request_id: A string specifying the request ID.'
| def _Dynamic_AddActions(self, request, response, request_id=None):
| del response, request_id
transaction = request.add_request_list()[0].transaction()
txn_actions = self.__tx_actions[transaction.handle()]
if ((len(txn_actions) + request.add_request_size()) > _MAX_ACTIONS_PER_TXN):
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST, ('Too ma... |
'Send a transaction request to commit a transaction to the
datastore server.'
| def _Dynamic_Commit(self, transaction, transaction_response, request_id=None):
| transaction.set_app(self.__app_id)
self._RemoteSend(transaction, transaction_response, 'Commit', request_id)
response = taskqueue_service_pb.TaskQueueAddResponse()
try:
for action in self.__tx_actions[transaction.handle()]:
try:
apiproxy_stub_map.MakeSyncCall('taskque... |
'Send a rollback request to the datastore server.'
| def _Dynamic_Rollback(self, transaction, transaction_response, request_id=None):
| transaction.set_app(self.__app_id)
try:
del self.__tx_actions[transaction.handle()]
except KeyError:
pass
self._RemoteSend(transaction, transaction_response, 'Rollback', request_id)
return transaction_response
|
'Get the schema of a particular kind of entity.'
| def _Dynamic_GetSchema(self, req, schema, request_id=None):
| del request_id
app_str = req.app()
self.__ValidateAppId(app_str)
schema.set_more_results(False)
|
'Send a request for allocation of IDs to the datastore server.'
| def _Dynamic_AllocateIds(self, request, response, request_id=None):
| self._RemoteSend(request, response, 'AllocateIds', request_id)
return response
|
'Create a new index. Currently stubbed out.'
| def _Dynamic_CreateIndex(self, index, id_response, request_id=None):
| if (index.id() != 0):
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST, 'New index id must be 0.')
self._RemoteSend(index, id_response, 'CreateIndex', request_id)
return id_response
|
'Gets the indices of the current app.
Args:
app_str: A api_base_pb.StringProto, the application identifier.
composite_indices: datastore_pb.CompositeIndices protocol buffer.
request_id: A string specifying the request ID.
Returns:
A datastore_pb.CompositesIndices containing the current indexes
used by this application.... | def _Dynamic_GetIndices(self, app_str, composite_indices, request_id=None):
| self._RemoteSend(app_str, composite_indices, 'GetIndices', request_id)
return composite_indices
|
'Updates the indices of the current app. Tells the AppScale datastore
server to build out the new index with existing data.
Args:
index: A datastore_pb.CompositeIndex, the composite index to update.
void: A entity_pb.VoidProto.
request_id: A string specifying the request ID.'
| def _Dynamic_UpdateIndex(self, index, void, request_id=None):
| self._RemoteSend(index, void, 'UpdateIndex', request_id)
return
|
'Deletes an index of the current app.
Args:
index: A entity_pb.CompositeIndex, the composite index to delete.
void: A entity_pb.VoidProto.
request_id: A string specifying the request ID.
Returns:
A entity_pb.VoidProto.'
| def _Dynamic_DeleteIndex(self, index, void, request_id=None):
| self._RemoteSend(index, void, 'DeleteIndex', request_id)
return void
|
'Ensure that the set of existing composite indexes matches index.yaml.
Create any new indexes, and delete indexes which are no longer required.
Args:
_open: Function used to open a file.'
| def _SetupIndexes(self, _open=open):
| if (not self.__root_path):
logging.warning('No index.yaml was loaded.')
return
index_yaml_file = os.path.join(self.__root_path, 'index.yaml')
if ((self.__cached_yaml[0] == index_yaml_file) and os.path.exists(index_yaml_file) and (os.path.getmtime(index_yaml_file) == self.__cached_ya... |
'Set dictionary item.
Args:
key: Key of new item. Key is case insensitive, so "d[\'Key\'] = value "
will replace previous values set by "d[\'key\'] = old_value".
item: Item to store.'
| def __setitem__(self, key, item):
| caseless_key = key.lower()
if (caseless_key in self.caseless_keys):
del self.data[self.caseless_keys[caseless_key]]
self.caseless_keys[caseless_key] = key
self.data[key] = item
|
'Get dictionary item.
Args:
key: Key of item to get. Key is case insensitive, so "d[\'Key\']" is the
same as "d[\'key\']".
Returns:
Item associated with key.'
| def __getitem__(self, key):
| return self.data[self.caseless_keys[key.lower()]]
|
'Remove item from dictionary.
Args:
key: Key of item to remove. Key is case insensitive, so "del d[\'Key\']" is
the same as "del d[\'key\']"'
| def __delitem__(self, key):
| caseless_key = key.lower()
del self.data[self.caseless_keys[caseless_key]]
del self.caseless_keys[caseless_key]
|
'Determine if dictionary has item with specific key.
Args:
key: Key to check for presence. Key is case insensitive, so
"d.has_key(\'Key\')" evaluates to the same value as "d.has_key(\'key\')".
Returns:
True if dictionary contains key, else False.'
| def has_key(self, key):
| return (key.lower() in self.caseless_keys)
|
'Same as \'has_key\', but used for \'in\' operator.\''
| def __contains__(self, key):
| return self.has_key(key)
|
'Get dictionary item, defaulting to another value if it does not exist.
Args:
key: Key of item to get. Key is case insensitive, so "d[\'Key\']" is the
same as "d[\'key\']".
failobj: Value to return if key not in dictionary.'
| def get(self, key, failobj=None):
| try:
cased_key = self.caseless_keys[key.lower()]
except KeyError:
return failobj
return self.data[cased_key]
|
'Update dictionary using values from another dictionary and keywords.
Args:
dict: Dictionary to update from.
kwargs: Keyword arguments to update from.'
| def update(self, dict=None, **kwargs):
| if dict:
try:
keys = dict.keys()
except AttributeError:
for (k, v) in dict:
self[k] = v
else:
for k in keys:
self[k] = dict[k]
if kwargs:
self.update(kwargs)
|
'Make a shallow, case sensitive copy of self.'
| def copy(self):
| return dict(self)
|
'Constructor.
Args:
response_proto: the URLFetchResponse proto buffer to wrap.'
| def __init__(self, response_proto):
| self.__pb = response_proto
self.content = response_proto.content()
self.status_code = response_proto.statuscode()
self.content_was_truncated = response_proto.contentwastruncated()
self.final_url = (response_proto.finalurl() or None)
self.header_msg = httplib.HTTPMessage(StringIO.StringIO(''.join... |
'Starts this background thread.'
| def start(self):
| if (not self._Thread__initialized):
raise RuntimeError('thread.__init__() not called')
if self._Thread__started.is_set():
raise RuntimeError('threads can only be started once')
with threading._active_limbo_lock:
threading._limbo[self] = self
try:
star... |
'Initializer.
Args:
service_name: Service name expected for all calls.
urlmatchers_to_fetch_functions: A list of two-element tuples.
The first element is a urlmatcher predicate function that takes
a url and determines a match. The second is a function that
can retrieve result for that url. If no match is found, a url i... | def __init__(self, service_name='urlfetch', urlmatchers_to_fetch_functions=None):
| super(URLFetchServiceStub, self).__init__(service_name, max_request_size=MAX_REQUEST_SIZE)
self._urlmatchers_to_fetch_functions = (urlmatchers_to_fetch_functions or [])
|
'Trivial implementation of URLFetchService::Fetch().
Args:
request: the fetch to perform, a URLFetchRequest
response: the fetch response, a URLFetchResponse'
| def _Dynamic_Fetch(self, request, response):
| if (len(request.url()) >= _MAX_URL_LENGTH):
logging.error(('URL is too long: %s...' % request.url()[:50]))
raise apiproxy_errors.ApplicationError(urlfetch_service_pb.URLFetchServiceError.INVALID_URL)
(protocol, host, path, query, fragment) = urlparse.urlsplit(request.url())
paylo... |
'Get the fetch function for a url.
Args:
url: A url to fetch from. str.
Returns:
A fetch function for this url.'
| def _GetFetchFunction(self, url):
| for (urlmatcher, fetch_function) in self._urlmatchers_to_fetch_functions:
if urlmatcher(url):
return fetch_function
return self._RetrieveURL
|
'Retrieves a URL over network.
Args:
url: String containing the URL to access.
payload: Request payload to send, if any; None if no payload.
If the payload is unicode, we assume it is utf-8.
method: HTTP method to use (e.g., \'GET\')
headers: List of additional header objects to use for the request.
request: A urlfetch... | @staticmethod
def _RetrieveURL(url, payload, method, headers, request, response, follow_redirects=True, deadline=_API_CALL_DEADLINE, validate_certificate=_API_CALL_VALIDATE_CERTIFICATE_DEFAULT):
| last_protocol = ''
last_host = ''
if isinstance(payload, unicode):
payload = payload.encode('utf-8')
for redirect_number in xrange((MAX_REDIRECTS + 1)):
parsed = urlparse.urlsplit(url)
(protocol, host, path, query, fragment) = parsed
port = urllib.splitport(urllib.splitus... |
'Cleans "unsafe" headers from the HTTP request, in place.
Args:
untrusted_headers: Set of untrusted headers names (all lowercase).
headers: List of Header objects. The list is modified in place.'
| def _SanitizeHttpHeaders(self, untrusted_headers, headers):
| prohibited_headers = [h.key() for h in headers if (h.key().lower() in untrusted_headers)]
if prohibited_headers:
logging.debug('Stripped prohibited headers from URLFetch request: %s', prohibited_headers)
for index in reversed(xrange(len(headers))):
if (headers[index... |
'Initializer.
Args:
login_url: String containing the URL to use for logging in.
logout_url: String containing the URL to use for logging out.
service_name: Service name expected for all calls.
auth_domain: The authentication domain for the service e.g. "gmail.com".
request_data: A apiproxy_stub.RequestData instance use... | def __init__(self, login_url=_DEFAULT_LOGIN_URL, logout_url=_DEFAULT_LOGOUT_URL, service_name='user', auth_domain=_DEFAULT_AUTH_DOMAIN, request_data=None):
| super(UserServiceStub, self).__init__(service_name, request_data=request_data)
self._login_url = login_url
self._logout_url = logout_url
self.__scopes = None
self.SetOAuthUser()
os.environ['AUTH_DOMAIN'] = auth_domain
|
'Set test OAuth user.
Determines what user is returned by requests to GetOAuthUser.
Args:
email: Email address of oauth user. None indicates that no oauth user
is authenticated.
domain: Domain of oauth user.
user_id: User ID of oauth user.
is_admin: Whether the user is an admin.
scopes: List of scopes that user is au... | def SetOAuthUser(self, email=_OAUTH_EMAIL, domain=_OAUTH_AUTH_DOMAIN, user_id=_OAUTH_USER_ID, is_admin=False, scopes=None, client_id=_OAUTH_CLIENT_ID):
| self.__email = email
self.__domain = domain
self.__user_id = user_id
self.__is_admin = is_admin
self.__scopes = scopes
self._client_id = client_id
|
'Trivial implementation of UserService.CreateLoginURL().
Args:
request: a CreateLoginURLRequest
response: a CreateLoginURLResponse
request_id: A unique string identifying the request associated with the
API call.'
| def _Dynamic_CreateLoginURL(self, request, response, request_id):
| response.set_login_url((self._login_url % urllib.quote(self._AddHostToContinueURL(request.destination_url(), request_id))))
|
'Trivial implementation of UserService.CreateLogoutURL().
Args:
request: a CreateLogoutURLRequest
response: a CreateLogoutURLResponse
request_id: A unique string identifying the request associated with the
API call.'
| def _Dynamic_CreateLogoutURL(self, request, response, request_id):
| response.set_logout_url((self._logout_url % urllib.quote(self._AddHostToContinueURL(request.destination_url(), request_id))))
|
'Trivial implementation of UserService.GetOAuthUser().
Args:
request: a GetOAuthUserRequest
response: a GetOAuthUserResponse
request_id: A unique string identifying the request associated with the
API call.'
| def _Dynamic_GetOAuthUser(self, request, response, request_id):
| if (self.__email is None):
raise apiproxy_errors.ApplicationError(user_service_pb.UserServiceError.OAUTH_INVALID_REQUEST)
else:
if (self.__scopes is not None):
if (request.scope() not in self.__scopes):
raise apiproxy_errors.ApplicationError(user_service_pb.UserServic... |
'Trivial implementation of UserService.CheckOAuthSignature().
Args:
unused_request: a CheckOAuthSignatureRequest
response: a CheckOAuthSignatureResponse
request_id: A unique string identifying the request associated with the
API call.'
| def _Dynamic_CheckOAuthSignature(self, unused_request, response, request_id):
| response.set_oauth_consumer_key(_OAUTH_CONSUMER_KEY)
|
'Adds the request host to the continue url if no host is specified.
Args:
continue_url: the URL which may or may not have a host specified
request_id: A unique string identifying the request associated with the
API call.
Returns:
string'
| def _AddHostToContinueURL(self, continue_url, request_id):
| (protocol, host, path, parameters, query, fragment) = urlparse.urlparse(continue_url)
if (host and protocol):
return continue_url
(protocol, host, _, _, _, _) = urlparse.urlparse(self.request_data.get_request_url(request_id))
if (path == ''):
path = '/'
return urlparse.urlunparse((pr... |
'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 either be delivered
to the webhook as the HTTP request body or fetched by workers for pull
queues. This is only allowed for POST, PUT and PULL methods.
name: Name to give the Task; if not specified, a name will be
auto-ge... | 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... |
'Resolve the values of the target parameter and the `Host\' header.
Requires that the attributes __target and __headers exist before this method
is called.
This function should only be called once from the __init__ function of the
Task class.
Raises:
InvalidTaskError: If the task is invalid.'
| def __resolve_hostname_and_target(self):
| if ('HTTP_HOST' not in os.environ):
logging.warning("The HTTP_HOST environment variable was not set, but is required to determine the correct value for the `Task.target' property. Please update your unit tests to specify a corr... |
'Calculate the value of the target parameter from a host header.
Args:
host: A string representing the hostname for this task.
Returns:
A string containing the target of this task, or the constant
DEFAULT_APP_VERSION if it is the default version.
If this code is running in a unit-test where the environment variable
`DE... | @staticmethod
def __target_from_host(host):
| default_hostname = app_identity.get_default_version_hostname()
if (default_hostname is None):
return _UNKNOWN_APP_VERSION
if host.endswith(default_hostname):
version_name = host[:(- (len(default_hostname) + 1))]
if version_name:
return version_name
return DEFAULT_APP_... |
'Calculate the value of the host header from a target.
Args:
target: A string representing the target hostname or the constant
DEFAULT_APP_VERSION.
Returns:
The string to be used as the host header, or None if it can not be
determined.'
| @staticmethod
def __host_from_target(target):
| default_hostname = app_identity.get_default_version_hostname()
if (default_hostname is None):
return None
if (target is DEFAULT_APP_VERSION):
return default_hostname
else:
return ('%s.%s' % (target, default_hostname))
|
'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=None):
| if (not current_time):
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 InvalidTa... |
'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 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 int microseconds timestamp when this Task will execute.'
| @property
def _eta_usec(self):
| return int(round((self.eta_posix * 1000000.0)))
|
'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 True if this Task will run on the queue\'s URL.'
| @property
def on_queue_url(self):
| return self.__default_url
|
'Returns the payload for this task, which may be None.'
| @property
def payload(self):
| return self.__payload
|
'Returns the name of the queue this Task is associated with.
Will be None if this Task has not yet been added to a queue.'
| @property
def queue_name(self):
| return self.__queue_name
|
'Returns the number of retries have been done on the task.'
| @property
def retry_count(self):
| return self.__retry_count
|
'Returns the TaskRetryOptions for this task, which may be None.'
| @property
def retry_options(self):
| return self.__retry_options
|
'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 tag for this Task.'
| @property
def tag(self):
| return self.__tag
|
'Returns the target for this Task.'
| @property
def target(self):
| return self.__target
|
'Returns the relative URL for this Task.'
| @property
def url(self):
| return self.__relative_url
|
'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
|
'Returns True if this Task has been successfully deleted.'
| @property
def was_deleted(self):
| return self.__deleted
|
'Asynchronously adds this Task to a queue. See Queue.add_async.'
| def add_async(self, queue_name=_DEFAULT_QUEUE, transactional=False, rpc=None):
| return Queue(queue_name).add_async(self, transactional, rpc)
|
'Adds this Task to a queue. See Queue.add.'
| def add(self, queue_name=_DEFAULT_QUEUE, transactional=False):
| return self.add_async(queue_name, transactional).get_result()
|
'Returns the parameters for this task.
Returns:
A dictionary of strings mapping parameter names to their values as
strings. If the same name parameter has several values then the value will
be a list of strings. For POST and PULL requests then the parameters are
extracted from the task payload. For all other methods, t... | def extract_params(self):
| if (self.__method in ('PULL', 'POST')):
query = self.__payload
else:
query = urlparse.urlparse(self.__relative_url).query
p = {}
if (not query):
return p
for (key, value) in cgi.parse_qsl(query, keep_blank_values=True, strict_parsing=True):
p.setdefault(key, []).appen... |
'Constructor.
Args:
queue: The Queue instance this QueueStatistics is for.
tasks: The number of tasks left.
oldest_eta_usec: The eta of the oldest non-completed task for the queue;
None if unknown.
executed_last_minute: The number of tasks executed in the last minute.
in_flight: The number of tasks that are currently e... | def __init__(self, queue, tasks, oldest_eta_usec=None, executed_last_minute=None, in_flight=None, enforced_rate=None):
| self.queue = queue
self.tasks = tasks
self.oldest_eta_usec = oldest_eta_usec
self.executed_last_minute = executed_last_minute
self.in_flight = in_flight
self.enforced_rate = enforced_rate
|
'Helper for converting from a FetchQeueueStatsResponse_QueueStats proto.
Args:
queue: A Queue instance.
response: a FetchQeueueStatsResponse_QueueStats instance.
Returns:
A new QueueStatistics instance.'
| @classmethod
def _ConstructFromFetchQueueStatsResponse(cls, queue, response):
| args = {'queue': queue, 'tasks': response.num_tasks()}
if (response.oldest_eta_usec() >= 0):
args['oldest_eta_usec'] = response.oldest_eta_usec()
else:
args['oldest_eta_usec'] = None
if response.has_scanner_info():
scanner_info = response.scanner_info()
args['executed_las... |
'Asynchronously get the queue details for multiple queues.
Args:
queue_or_queues: An iterable of Queue instances, or an iterable of
strings corresponding to queue names, or a Queue instance or a string
corresponding to a queue name.
rpc: An optional UserRPC object.
Returns:
A UserRPC object, call get_result to complete... | @classmethod
def fetch_async(cls, queue_or_queues, rpc=None):
| wants_list = True
if isinstance(queue_or_queues, basestring):
queue_or_queues = [queue_or_queues]
wants_list = False
try:
queues_list = [queue for queue in queue_or_queues]
except TypeError:
queues_list = [queue_or_queues]
wants_list = False
contains_strs = an... |
'Get the queue details for multiple queues.
Args:
queue_or_queues: An iterable of Queue instances, or an iterable of
strings corresponding to queue names, or a Queue instance or a string
corresponding to a queue name.
deadline: The maximum number of seconds to wait before aborting the
method call.
Returns:
If an iterab... | @classmethod
def fetch(cls, queue_or_queues, deadline=10):
| _ValidateDeadline(deadline)
if (not queue_or_queues):
return []
rpc = create_rpc(deadline)
cls.fetch_async(queue_or_queues, rpc)
return rpc.get_result()
|
'Internal implementation of fetch stats where queues must be a list.'
| @classmethod
def _FetchMultipleQueues(cls, queues, multiple, rpc=None):
| def ResultHook(rpc):
'Process the TaskQueueFetchQueueStatsResponse.'
try:
rpc.check_success()
except apiproxy_errors.ApplicationError as e:
raise _TranslateError(e.application_error, e.error_detail)
assert (len(queues) == rpc.response.queuestats_size()),... |
'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:
Error-subclass on application errors.'
| 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)
... |
'Asynchronously deletes a Task or list of Tasks in this Queue, by name.
This function is identical to delete_tasks_by_name() except that it returns
an asynchronous object. You can call get_result() on the return value to
block on the call.
Args:
task_name: A string corresponding to a task name, or an iterable of
string... | def delete_tasks_by_name_async(self, task_name, rpc=None):
| if isinstance(task_name, str):
return self.delete_tasks_async(Task(name=task_name), rpc)
else:
tasks = [Task(name=name) for name in task_name]
return self.delete_tasks_async(tasks, rpc)
|
'Deletes a Task or list of Tasks in this Queue, by name.
When multiple tasks are specified, an exception will be raised if any
individual task fails to be deleted.
Args:
task_name: A string corresponding to a task name, or an iterable of
strings corresponding to task names.
Returns:
If an iterable (other than string) i... | def delete_tasks_by_name(self, task_name):
| return self.delete_tasks_by_name_async(task_name).get_result()
|
'Asynchronously deletes a Task or list of Tasks in this Queue.
This function is identical to delete_tasks() except that it returns an
asynchronous object. You can call get_result() on the return value to block
on the call.
Args:
task: A Task instance or a list of Task instances that will be deleted
from the Queue.
rpc:... | def delete_tasks_async(self, task, rpc=None):
| try:
tasks = list(iter(task))
except TypeError:
tasks = [task]
multiple = False
else:
multiple = True
return self.__DeleteTasks(tasks, multiple, rpc)
|
'Deletes a Task or list of Tasks in this Queue.
When multiple tasks are specified, an exception will be raised if any
individual task fails to be deleted. Check the task.was_deleted property.
Task name is the only task attribute used to select tasks for deletion. If
there is any task with was_deleted property set to Tr... | def delete_tasks(self, task):
| return self.delete_tasks_async(task).get_result()
|
'Internal implementation of delete_tasks_async(), tasks must be a list.'
| def __DeleteTasks(self, tasks, multiple, rpc=None):
| def ResultHook(rpc):
'Process the TaskQueueDeleteResponse.'
try:
rpc.check_success()
except apiproxy_errors.ApplicationError as e:
raise _TranslateError(e.application_error, e.error_detail)
assert (rpc.response.result_size() == len(tasks)), ('expected ... |
'Asynchronously leases a number of tasks from the Queue.
This function is identical to lease_tasks() except that it returns an
asynchronous object. You can call get_result() on the return value to block
on the call.
Args:
lease_seconds: Number of seconds to lease the tasks.
max_tasks: Max number of tasks to lease from ... | def lease_tasks_async(self, lease_seconds, max_tasks, rpc=None):
| lease_seconds = self._ValidateLeaseSeconds(lease_seconds)
self._ValidateMaxTasks(max_tasks)
request = taskqueue_service_pb.TaskQueueQueryAndOwnTasksRequest()
response = taskqueue_service_pb.TaskQueueQueryAndOwnTasksResponse()
request.set_queue_name(self.__name)
request.set_lease_seconds(lease_se... |
'Leases a number of tasks from the Queue for a period of time.
This method can only be performed on a pull Queue. Any non-pull tasks in
the pull Queue will be converted into pull tasks when being leased. If
fewer than max_tasks are available, all available tasks will be returned.
The lease_tasks method supports leasing... | def lease_tasks(self, lease_seconds, max_tasks, deadline=10):
| _ValidateDeadline(deadline)
rpc = create_rpc(deadline)
self.lease_tasks_async(lease_seconds, max_tasks, rpc)
return rpc.get_result()
|
'Asynchronously leases a number of tasks from the Queue.
This function is identical to lease_tasks_by_tag() except that it returns an
asynchronous object. You can call get_result() on the return value to block
on the call.
Args:
lease_seconds: Number of seconds to lease the tasks.
max_tasks: Max number of tasks to leas... | def lease_tasks_by_tag_async(self, lease_seconds, max_tasks, tag=None, rpc=None):
| lease_seconds = self._ValidateLeaseSeconds(lease_seconds)
self._ValidateMaxTasks(max_tasks)
request = taskqueue_service_pb.TaskQueueQueryAndOwnTasksRequest()
response = taskqueue_service_pb.TaskQueueQueryAndOwnTasksResponse()
request.set_queue_name(self.__name)
request.set_lease_seconds(lease_se... |
'Leases a number of tasks from the Queue for a period of time.
This method can only be performed on a pull Queue. Any non-pull tasks in
the pull Queue will be converted into pull tasks when being leased. If
fewer than max_tasks are available, all available tasks will be returned.
The lease_tasks method supports leasing... | def lease_tasks_by_tag(self, lease_seconds, max_tasks, tag=None, deadline=10):
| _ValidateDeadline(deadline)
rpc = create_rpc(deadline)
self.lease_tasks_by_tag_async(lease_seconds, max_tasks, tag, rpc)
return rpc.get_result()
|
'Asynchronously adds a Task or list of Tasks into this Queue.
This function is identical to add() except that it returns an asynchronous
object. You can call get_result() on the return value to block on the call.
Args:
task: A Task instance or a list of Task instances that will be added to
the queue.
transactional: If ... | def add_async(self, task, transactional=False, rpc=None):
| try:
tasks = list(iter(task))
except TypeError:
tasks = [task]
multiple = False
else:
multiple = True
has_push_task = False
has_pull_task = False
for task in tasks:
if (task.method == 'PULL'):
has_pull_task = True
else:
has_... |
'Adds a Task or list of Tasks into 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.... | def add(self, task, transactional=False):
| if task:
return self.add_async(task, transactional).get_result()
else:
return []
|
'Internal implementation of adding tasks where tasks must be a list.'
| def __AddTasks(self, tasks, transactional, fill_request, multiple, rpc=None):
| def ResultHook(rpc):
'Process the TaskQueueBulkAddResponse.'
try:
rpc.check_success()
except apiproxy_errors.ApplicationError as e:
raise _TranslateError(e.application_error, e.error_detail)
assert (rpc.response.taskresult_size() == len(tasks)), ('expect... |
'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 push 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 inf... | def __FillAddPushTasksRequest(self, task, task_request, transactional):
| task_request.set_mode(taskqueue_service_pb.TaskQueueMode.PUSH)
self.__FillTaskCommon(task, task_request, transactional)
adjusted_url = task.url
if task.on_queue_url:
adjusted_url = (self.__url + task.url)
task_request.set_method(_METHOD_MAP.get(task.method))
task_request.set_url(adjusted... |
'Populates a TaskQueueAddRequest with the data from a pull 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 inf... | def __FillAddPullTasksRequest(self, task, task_request, transactional):
| task_request.set_mode(taskqueue_service_pb.TaskQueueMode.PULL)
self.__FillTaskCommon(task, task_request, transactional)
if (task.payload is not None):
task_request.set_body(task.payload)
else:
raise BadTaskStateError('Pull task must have a payload')
|
'Fills common fields for both push tasks and pull tasks.'
| def __FillTaskCommon(self, task, task_request, transactional):
| if self._app:
task_request.set_app_id(self._app)
task_request.set_queue_name(self.__name)
task_request.set_eta_usec(task._eta_usec)
if task.name:
task_request.set_task_name(task.name)
else:
task_request.set_task_name('')
if task.tag:
task_request.set_tag(task.tag)... |
'Returns the name of this queue.'
| @property
def name(self):
| return self.__name
|
'Modifies the lease of a task in this queue.
Args:
task: A task instance that will have its lease modified.
lease_seconds: Number of seconds, from the current time, that the task
lease will be modified to. If lease_seconds is 0, then the task lease
is removed and the task will be available for leasing again using
the l... | def modify_task_lease(self, task, lease_seconds):
| lease_seconds = self._ValidateLeaseSeconds(lease_seconds)
request = taskqueue_service_pb.TaskQueueModifyTaskLeaseRequest()
response = taskqueue_service_pb.TaskQueueModifyTaskLeaseResponse()
request.set_queue_name(self.__name)
request.set_task_name(task.name)
request.set_eta_usec(task._eta_usec)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.