desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'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):
| self._GetGroup(_GetAppId(request)).UpdateQueue_Rpc(request, unused_response)
|
'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):
| self._GetGroup(_GetAppId(request)).FetchQueues_Rpc(request, response)
|
'Local \'random\' implementation of the TaskQueueService.FetchQueueStats.
This implementation loads some stats from the task 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 taskq... | def _Dynamic_FetchQueueStats(self, request, response):
| self._GetGroup(_GetAppId(request)).FetchQueueStats_Rpc(request, response)
|
'Local implementation of the TaskQueueService.QueryTasks RPC.
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.TaskQueueQueryTasksRequest.
response: A taskqueue_service_pb.TaskQueueQueryTasksResp... | def _Dynamic_QueryTasks(self, request, response):
| self._GetGroup(_GetAppId(request)).QueryTasks_Rpc(request, response)
|
'Local implementation of the TaskQueueService.FetchTask RPC.
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.TaskQueueFetchTaskRequest.
response: A taskqueue_service_pb.TaskQueueFetchTaskRespons... | def _Dynamic_FetchTask(self, request, response):
| self._GetGroup(_GetAppId(request)).FetchTask_Rpc(request, response)
|
'Local delete implementation of TaskQueueService.Delete.
Deletes tasks from the task store. A 1/20 chance of a transient error.
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.TaskQueueDeleteReq... | def _Dynamic_Delete(self, request, response):
| self._GetGroup(_GetAppId(request)).Delete_Rpc(request, response)
|
'Local force run implementation of TaskQueueService.ForceRun.
Forces running of a task in a queue. This will fail randomly for testing if
the app id is non-empty.
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_ForceRun(self, request, response):
| if (_GetAppId(request) is not None):
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:
... |
'Local delete implementation of TaskQueueService.DeleteQueue.
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.TaskQueueDeleteQueueRequest.
response: A taskqueue_service_pb.TaskQueueDeleteQueueRe... | def _Dynamic_DeleteQueue(self, request, response):
| app_id = _GetAppId(request)
if (app_id is None):
raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.PERMISSION_DENIED)
self._GetGroup(app_id).DeleteQueue_Rpc(request, response)
|
'Local pause implementation of TaskQueueService.PauseQueue.
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.TaskQueuePauseQueueRequest.
response: A taskqueue_service_pb.TaskQueuePauseQueueRespon... | def _Dynamic_PauseQueue(self, request, response):
| app_id = _GetAppId(request)
if (app_id is None):
raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.PERMISSION_DENIED)
self._GetGroup(app_id).PauseQueue_Rpc(request, response)
|
'Local purge implementation of TaskQueueService.PurgeQueue.
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.TaskQueuePurgeQueueRequest.
response: A taskqueue_service_pb.TaskQueuePurgeQueueRespon... | def _Dynamic_PurgeQueue(self, request, response):
| self._GetGroup(_GetAppId(request)).PurgeQueue_Rpc(request, response)
|
'Local delete implementation of TaskQueueService.DeleteGroup.
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.TaskQueueDeleteGroupRequest.
response: A taskqueue_service_pb.TaskQueueDeleteGroupRe... | def _Dynamic_DeleteGroup(self, request, response):
| app_id = _GetAppId(request)
if (app_id is None):
raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.PERMISSION_DENIED)
if (app_id in self._queues):
del self._queues[app_id]
else:
raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueS... |
'Local implementation of TaskQueueService.UpdateStorageLimit.
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.TaskQueueUpdateStorageLimitRequest.
response: A taskqueue_service_pb.TaskQueueUpdate... | def _Dynamic_UpdateStorageLimit(self, request, response):
| if (_GetAppId(request) is None):
raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.PERMISSION_DENIED)
if ((request.limit() < 0) or (request.limit() > (1000 * (1024 ** 4)))):
raise apiproxy_errors.ApplicationError(taskqueue_service_pb.TaskQueueServiceError.INVALID_... |
'Local implementation of TaskQueueService.QueryAndOwnTasks.
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.TaskQueueQueryAndOwnTasksRequest.
response: A taskqueue_service_pb.TaskQueueQueryAndOw... | def _Dynamic_QueryAndOwnTasks(self, request, response):
| self._GetGroup().QueryAndOwnTasks_Rpc(request, response)
|
'Local implementation of TaskQueueService.ModifyTaskLease.
Args:
request: A taskqueue_service_pb.TaskQueueModifyTaskLeaseRequest.
response: A taskqueue_service_pb.TaskQueueModifyTaskLeaseResponse.
Raises:
InvalidQueueModeError: If target queue is not a pull queue.'
| def _Dynamic_ModifyTaskLease(self, request, response):
| self._GetGroup().ModifyTaskLease_Rpc(request, response)
|
'Get the tasks in the task queue with filters.
Args:
url: A URL that all returned tasks should point at.
name: The name of all returned tasks.
queue_names: A list of queue names to retrieve tasks from. If left blank
this will get default to all queues available.
Returns:
A list of taskqueue.Task objects.'
| def get_filtered_tasks(self, url=None, name=None, queue_names=None):
| all_queue_names = [queue['name'] for queue in self.GetQueues()]
if isinstance(queue_names, basestring):
queue_names = [queue_names]
if (queue_names is None):
queue_names = all_queue_names
task_dicts = []
for queue_name in queue_names:
if (queue_name in all_queue_names):
... |
'Constructor.
Args:
payload: Maps to attribute of the same name.
charset: Maps to attribute of the same name.
encoding: Maps to attribute of the same name.'
| def __init__(self, payload, charset=None, encoding=None):
| self.payload = payload
self.charset = charset
self.encoding = encoding
|
'Attempt to decode the encoded data.
Attempt to use pythons codec library to decode the payload. All
exceptions are passed back to the caller.
Returns:
Binary or unicode version of payload content.'
| def decode(self):
| payload = self.payload
if (self.encoding and (self.encoding.lower() != '7bit')):
try:
payload = payload.decode(self.encoding)
except LookupError:
raise UnknownEncodingError(('Unknown decoding %s.' % self.encoding))
except (Exception, Error) as e:
... |
'Equality operator.
Args:
other: The other EncodedPayload object to compare with. Comparison
with other object types are not implemented.
Returns:
True of payload and encodings are equal, else false.'
| def __eq__(self, other):
| if isinstance(other, EncodedPayload):
return ((self.payload == other.payload) and (self.charset == other.charset) and (self.encoding == other.encoding))
else:
return NotImplemented
|
'Copy contents to MIME message payload.
If no content transfer encoding is specified, and the character set does
not equal the over-all message encoding, the payload will be base64
encoded.
Args:
mime_message: Message instance to receive new payload.'
| def copy_to(self, mime_message):
| if self.encoding:
mime_message['content-transfer-encoding'] = self.encoding
mime_message.set_payload(self.payload, self.charset)
|
'Convert to MIME message.
Returns:
MIME message instance of payload.'
| def to_mime_message(self):
| mime_message = email.Message.Message()
self.copy_to(mime_message)
return mime_message
|
'String representation of encoded message.
Returns:
MIME encoded representation of encoded payload as an independent message.'
| def __str__(self):
| return str(self.to_mime_message())
|
'Basic representation of encoded payload.
Returns:
Payload itself is represented by its hash value.'
| def __repr__(self):
| result = ('<EncodedPayload payload=#%d' % hash(self.payload))
if self.charset:
result += (' charset=%s' % self.charset)
if self.encoding:
result += (' encoding=%s' % self.encoding)
return (result + '>')
|
'Initialize Email message.
Creates new MailMessage protocol buffer and initializes it with any
keyword arguments.
Args:
mime_message: MIME message to initialize from. If instance of
email.Message.Message will take ownership as original message.
kw: List of keyword properties as defined by PROPERTIES.'
| def __init__(self, mime_message=None, **kw):
| if mime_message:
mime_message = _parse_mime_message(mime_message)
self.update_from_mime_message(mime_message)
self.__original = mime_message
self.initialize(**kw)
|
'Get original MIME message from which values were set.'
| @property
def original(self):
| return self.__original
|
'Keyword initialization.
Used to set all fields of the email message using keyword arguments.
Args:
kw: List of keyword properties as defined by PROPERTIES.'
| def initialize(self, **kw):
| for (name, value) in kw.iteritems():
setattr(self, name, value)
|
'Check if EmailMessage is properly initialized.
Test used to determine if EmailMessage meets basic requirements
for being used with the mail API. This means that the following
fields must be set or have at least one value in the case of
multi value fields:
- Subject must be set.
- A recipient must be specified.
- Must... | def check_initialized(self):
| if (not hasattr(self, 'sender')):
raise MissingSenderError()
found_body = False
try:
body = self.body
except AttributeError:
pass
else:
if isinstance(body, EncodedPayload):
body.decode()
found_body = True
try:
html = self.html
excep... |
'Determine if EmailMessage is properly initialized.
Returns:
True if message is properly initializes, otherwise False.'
| def is_initialized(self):
| try:
self.check_initialized()
return True
except Error:
return False
|
'Convert mail message to protocol message.
Unicode strings are converted to UTF-8 for all fields.
This method is overriden by EmailMessage to support the sender fields.
Returns:
MailMessage protocol version of mail message.
Raises:
Passes through decoding errors that occur when using when decoding
EncodedPayload object... | def ToProto(self):
| self.check_initialized()
message = mail_service_pb.MailMessage()
message.set_sender(_to_str(self.sender))
if hasattr(self, 'reply_to'):
message.set_replyto(_to_str(self.reply_to))
if hasattr(self, 'subject'):
message.set_subject(_to_str(self.subject))
else:
message.set_su... |
'Generate a MIMEMultitype message from EmailMessage.
Calls MailMessageToMessage after converting self to protocol
buffer. Protocol buffer is better at handing corner cases
than EmailMessage class.
Returns:
MIMEMultitype representing the provided MailMessage.
Raises:
Appropriate exception for initialization failure.
In... | def to_mime_message(self):
| return mail_message_to_mime_message(self.ToProto())
|
'Send email message.
Send properly initialized email message via email API.
Args:
make_sync_call: Method which will make synchronous call to api proxy.
Raises:
Errors defined in this file above.'
| def send(self, make_sync_call=apiproxy_stub_map.MakeSyncCall):
| message = self.ToProto()
response = api_base_pb.VoidProto()
try:
make_sync_call('mail', self._API_CALL, message, response)
except apiproxy_errors.ApplicationError as e:
if (e.application_error in ERROR_MAP):
raise ERROR_MAP[e.application_error](e.error_detail)
raise e... |
'Checks values going to attachment field.
Mainly used to check type safety of the values. Each value of the list
must be a pair of the form (file_name, data), and both values a string
type.
Args:
attachments: Collection of attachment tuples.
Raises:
TypeError if values are not string type.'
| def _check_attachments(self, attachments):
| if ((len(attachments) == 2) and isinstance(attachments[0], basestring)):
self._check_attachment(attachments)
else:
for attachment in attachments:
self._check_attachment(attachment)
|
'Property setting access control.
Controls write access to email fields.
Args:
attr: Attribute to access.
value: New value for field.
Raises:
ValueError: If provided with an empty field.
AttributeError: If not an allowed assignment field.'
| def __setattr__(self, attr, value):
| if (not attr.startswith('_EmailMessageBase')):
if (attr in ['sender', 'reply_to']):
check_email_valid(value, attr)
if ((not value) and (not (attr in self.ALLOWED_EMPTY_PROPERTIES))):
raise ValueError(("May not set empty value for '%s'" % attr))
if (a... |
'Add body to email from payload.
Will overwrite any existing default plain or html body.
Args:
content_type: Content-type of body.
payload: Payload to store body as.'
| def _add_body(self, content_type, payload):
| if (content_type == 'text/plain'):
self.body = payload
elif (content_type == 'text/html'):
self.html = payload
|
'Update payload of mail message from mime_message.
This function works recusively when it receives a multipart body.
If it receives a non-multi mime object, it will determine whether or
not it is an attachment by whether it has a filename or not. Attachments
and bodies are then wrapped in EncodedPayload with the corre... | def _update_payload(self, mime_message):
| payload = mime_message.get_payload()
if payload:
if (mime_message.get_content_maintype() == 'multipart'):
for alternative in payload:
self._update_payload(alternative)
else:
filename = mime_message.get_param('filename', header='content-disposition')
... |
'Copy information from a mime message.
Set information of instance to values of mime message. This method
will only copy values that it finds. Any missing values will not
be copied, nor will they overwrite old values with blank values.
This object is not guaranteed to be initialized after this call.
Args:
mime_messag... | def update_from_mime_message(self, mime_message):
| mime_message = _parse_mime_message(mime_message)
sender = _decode_and_join_header(mime_message['from'])
if sender:
self.sender = sender
reply_to = _decode_and_join_header(mime_message['reply-to'])
if reply_to:
self.reply_to = reply_to
subject = _decode_and_join_header(mime_messag... |
'Iterate over all bodies.
Yields:
Tuple (content_type, payload) for html and body in that order.'
| def bodies(self, content_type=None):
| if ((not content_type) or (content_type == 'text') or (content_type == 'text/html')):
try:
(yield ('text/html', self.html))
except AttributeError:
pass
if ((not content_type) or (content_type == 'text') or (content_type == 'text/plain')):
try:
(yield (... |
'Provide additional checks to ensure recipients have been specified.
Raises:
MissingRecipientError when no recipients specified in to, cc or bcc.'
| def check_initialized(self):
| if ((not hasattr(self, 'to')) and (not hasattr(self, 'cc')) and (not hasattr(self, 'bcc'))):
raise MissingRecipientsError()
super(EmailMessage, self).check_initialized()
|
'Does addition conversion of recipient fields to protocol buffer.
Returns:
MailMessage protocol version of mail message including sender fields.'
| def ToProto(self):
| message = super(EmailMessage, self).ToProto()
for (attribute, adder) in (('to', message.add_to), ('cc', message.add_cc), ('bcc', message.add_bcc)):
if hasattr(self, attribute):
for address in _email_sequence(getattr(self, attribute)):
adder(_to_str(address))
for (name, va... |
'Provides additional checks on recipient fields.'
| def __setattr__(self, attr, value):
| if (attr in ['to', 'cc', 'bcc']):
if isinstance(value, basestring):
if ((value == '') and getattr(self, 'ALLOW_BLANK_EMAIL', False)):
return
check_email_valid(value, attr)
else:
for address in value:
check_email_valid(address, attr)... |
'Copy information from a mime message.
Update fields for recipients.
Args:
mime_message: email.Message instance to copy information from.'
| def update_from_mime_message(self, mime_message):
| mime_message = _parse_mime_message(mime_message)
super(EmailMessage, self).update_from_mime_message(mime_message)
to = _decode_address_list_field(mime_message.get_all('to'))
if to:
self.to = to
cc = _decode_address_list_field(mime_message.get_all('cc'))
if cc:
self.cc = cc
bc... |
'Update values from MIME message.
Copies over date values.
Args:
mime_message: email.Message instance to copy information from.'
| def update_from_mime_message(self, mime_message):
| mime_message = _parse_mime_message(mime_message)
super(InboundEmailMessage, self).update_from_mime_message(mime_message)
for (property, header) in InboundEmailMessage.__HEADER_PROPERTIES.iteritems():
value = mime_message[header]
if value:
setattr(self, property, value)
|
'Add body to inbound message.
Method is overidden to handle incoming messages that have more than one
plain or html bodies or has any unidentified bodies.
This method will not overwrite existing html and body values. This means
that when updating, the text and html bodies that are first in the MIME
document order are ... | def _add_body(self, content_type, payload):
| if (((content_type == 'text/plain') and (not hasattr(self, 'body'))) or ((content_type == 'text/html') and (not hasattr(self, 'html')))):
super(InboundEmailMessage, self)._add_body(content_type, payload)
else:
try:
alternate_bodies = self.alternate_bodies
except AttributeErro... |
'Iterate over all bodies.
Args:
content_type: Content type to filter on. Allows selection of only
specific types of content. Can be just the base type of the content
type. For example:
content_type = \'text/html\' # Matches only HTML content.
content_type = \'text\' # Matches text of any kind.
Yields:
Tuple (... | def bodies(self, content_type=None):
| main_bodies = super(InboundEmailMessage, self).bodies(content_type)
for (payload_type, payload) in main_bodies:
(yield (payload_type, payload))
partial_type = bool((content_type and (content_type.find('/') < 0)))
try:
for (payload_type, payload) in self.alternate_bodies:
if c... |
'Convert to MIME message.
Adds additional headers from inbound email.
Returns:
MIME message instance of payload.'
| def to_mime_message(self):
| mime_message = super(InboundEmailMessage, self).to_mime_message()
for (property, header) in InboundEmailMessage.__HEADER_PROPERTIES.iteritems():
try:
mime_message[header] = getattr(self, property)
except AttributeError:
pass
return mime_message
|
'Initializer.
Args:
gettime: time.time()-like function used for testing.
service_name: Service name expected for all calls.'
| def __init__(self, gettime=time.time, service_name='memcache'):
| super(MemcacheService, self).__init__(service_name)
self._gettime = gettime
self._memcache = None
self.setupMemcacheClient()
|
'Sets up the memcache client.'
| def setupMemcacheClient(self):
| if os.path.exists(self.APPSCALE_MEMCACHE_FILE):
memcache_file = open(self.APPSCALE_MEMCACHE_FILE, 'r')
all_ips = memcache_file.read().split('\n')
memcache_file.close()
else:
all_ips = ['localhost']
memcaches = [((ip + ':') + self.MEMCACHE_PORT) for ip in all_ips if (ip != '')... |
'Implementation of gets for memcache.
Args:
request: A MemcacheGetRequest protocol buffer.
response: A MemcacheGetResponse protocol buffer.'
| def _Dynamic_Get(self, request, response):
| for key in set(request.key_list()):
internal_key = self._GetKey(request.name_space(), key)
value = self._memcache.get(internal_key)
if (value is None):
continue
flags = 0
(stored_flags, cas_id, stored_value) = cPickle.loads(value)
flags |= stored_flags
... |
'Implementation of sets for memcache.
Args:
request: A MemcacheSetRequest.
response: A MemcacheSetResponse.'
| def _Dynamic_Set(self, request, response):
| for item in request.item_list():
key = self._GetKey(request.name_space(), item.key())
set_policy = item.set_policy()
old_entry = self._memcache.get(key)
cas_id = 0
if old_entry:
(_, cas_id, _) = cPickle.loads(old_entry)
set_status = MemcacheSetResponse.NOT... |
'Implementation of delete in memcache.
Args:
request: A MemcacheDeleteRequest protocol buffer.
response: A MemcacheDeleteResponse protocol buffer.'
| def _Dynamic_Delete(self, request, response):
| for item in request.item_list():
key = self._GetKey(request.name_space(), item.key())
entry = self._memcache.get(key)
delete_status = MemcacheDeleteResponse.DELETED
if (entry is None):
delete_status = MemcacheDeleteResponse.NOT_FOUND
else:
self._memcac... |
'Internal function for incrementing from a MemcacheIncrementRequest.
Args:
namespace: A string containing the namespace for the request,
if any. Pass an empty string if there is no namespace.
request: A MemcacheIncrementRequest instance.
Returns:
An integer or long if the offset was successful, None on error.'
| def _Increment(self, namespace, request):
| if (not request.delta()):
return None
cas_id = 0
key = self._GetKey(namespace, request.key())
value = self._memcache.get(key)
if (value is None):
if (not request.has_initial_value()):
return None
(flags, cas_id, stored_value) = (TYPE_INT, cas_id, str(request.initi... |
'Implementation of increment for memcache.
Args:
request: A MemcacheIncrementRequest protocol buffer.
response: A MemcacheIncrementResponse protocol buffer.'
| def _Dynamic_Increment(self, request, response):
| new_value = self._Increment(request.name_space(), request)
if (new_value is None):
raise apiproxy_errors.ApplicationError(memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR)
response.set_new_value(new_value)
|
'Implementation of batch increment for memcache.
Args:
request: A MemcacheBatchIncrementRequest protocol buffer.
response: A MemcacheBatchIncrementResponse protocol buffer.'
| def _Dynamic_BatchIncrement(self, request, response):
| namespace = request.name_space()
for request_item in request.item_list():
new_value = self._Increment(namespace, request_item)
item = response.add_item()
if (new_value is None):
item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED)
else:
item.se... |
'Implementation of MemcacheService::FlushAll().
Args:
request: A MemcacheFlushRequest.
response: A MemcacheFlushResponse.'
| def _Dynamic_FlushAll(self, request, response):
| self._memcache.flush_all()
|
'Implementation of MemcacheService::Stats().
Args:
request: A MemcacheStatsRequest.
response: A MemcacheStatsResponse.'
| def _Dynamic_Stats(self, request, response):
| stats = response.mutable_stats()
num_servers = 0
hits_total = 0
misses_total = 0
byte_hits_total = 0
items_total = 0
bytes_total = 0
time_total = 0
def get_stats_value(stats_dict, key, _type=int):
' Gets statisical values and makes sure the key is ... |
'Used to get the Memcache key. It is encoded because the sdk
allows special characters but the Memcache client does not.
The key is hashed if it is longer than the max key size. This may lead
to collisions.
Args:
namespace: The namespace as provided by the application.
key: The key as provided by the application.
Retur... | def _GetKey(self, namespace, key):
| appname = os.environ['APPNAME']
internal_key = ((((appname + '__') + namespace) + '__') + key)
server_key = base64.b64encode(internal_key)
if (len(server_key) > MAX_KEY_SIZE):
server_key = hashlib.sha1(server_key).hexdigest()
return server_key
|
'Initializer.
Args:
value: String containing the data for this entry.
expiration: Number containing the expiration time or offset in seconds
for this entry.
flags: Opaque flags used by the memcache implementation.
cas_id: Unique Compare-And-Swap ID.
gettime: Used for testing. Function that works like time.time().'
| def __init__(self, value, expiration, flags, cas_id, gettime):
| assert isinstance(value, basestring)
assert (len(value) <= memcache.MAX_VALUE_SIZE)
assert isinstance(expiration, (int, long))
self._gettime = gettime
self.value = value
self.flags = flags
self.cas_id = cas_id
self.created_time = self._gettime()
self.will_expire = (expiration != 0)
... |
'Sets the expiration for this entry.
Args:
expiration: Number containing the expiration time or offset in seconds
for this entry. If expiration is above one month, then it\'s considered
an absolute time since the UNIX epoch.'
| def _SetExpiration(self, expiration):
| if (expiration > (86400 * 30)):
self.expiration_time = expiration
else:
self.expiration_time = (self._gettime() + expiration)
|
'Returns True if this entry has expired; False otherwise.'
| def CheckExpired(self):
| return (self.will_expire and (self._gettime() >= self.expiration_time))
|
'Marks this entry as deleted and locks it for the expiration time.
Used to implement memcache\'s delete timeout behavior.
Args:
timeout: Parameter originally passed to memcache.delete or
memcache.delete_multi to control deletion timeout.'
| def ExpireAndLock(self, timeout):
| self.will_expire = True
self.locked = True
self._SetExpiration(timeout)
|
'Returns True if this entry was deleted but has not yet timed out.'
| def CheckLocked(self):
| return (self.locked and (not self.CheckExpired()))
|
'Initializer.
Args:
gettime: time.time()-like function used for testing.
service_name: Service name expected for all calls.'
| def __init__(self, gettime=time.time, service_name='memcache'):
| super(MemcacheServiceStub, self).__init__(service_name, max_request_size=MAX_REQUEST_SIZE)
self._next_cas_id = 1
self._gettime = (lambda : int(gettime()))
self._ResetStats()
self._the_cache = {}
|
'Resets statistics information.'
| def _ResetStats(self):
| self._hits = 0
self._misses = 0
self._byte_hits = 0
self._cache_creation_time = self._gettime()
|
'Retrieves a CacheEntry from the cache if it hasn\'t expired.
Does not take deletion timeout into account.
Args:
namespace: The namespace that keys are stored under.
key: The key to retrieve from the cache.
Returns:
The corresponding CacheEntry instance, or None if it was not found or
has already expired.'
| def _GetKey(self, namespace, key):
| namespace_dict = self._the_cache.get(namespace, None)
if (namespace_dict is None):
return None
entry = namespace_dict.get(key, None)
if (entry is None):
return None
elif entry.CheckExpired():
del namespace_dict[key]
return None
else:
return entry
|
'Implementation of MemcacheService::Get().
Args:
request: A MemcacheGetRequest.
response: A MemcacheGetResponse.'
| def _Dynamic_Get(self, request, response):
| namespace = request.name_space()
keys = set(request.key_list())
for key in keys:
entry = self._GetKey(namespace, key)
if ((entry is None) or entry.CheckLocked()):
self._misses += 1
continue
self._hits += 1
self._byte_hits += len(entry.value)
it... |
'Implementation of MemcacheService::Set().
Args:
request: A MemcacheSetRequest.
response: A MemcacheSetResponse.'
| def _Dynamic_Set(self, request, response):
| namespace = request.name_space()
for item in request.item_list():
key = item.key()
set_policy = item.set_policy()
old_entry = self._GetKey(namespace, key)
set_status = MemcacheSetResponse.NOT_STORED
if ((set_policy == MemcacheSetRequest.SET) or ((set_policy == MemcacheSet... |
'Implementation of MemcacheService::Delete().
Args:
request: A MemcacheDeleteRequest.
response: A MemcacheDeleteResponse.'
| def _Dynamic_Delete(self, request, response):
| namespace = request.name_space()
for item in request.item_list():
key = item.key()
entry = self._GetKey(namespace, key)
delete_status = MemcacheDeleteResponse.DELETED
if (entry is None):
delete_status = MemcacheDeleteResponse.NOT_FOUND
elif (item.delete_time()... |
'Internal function for incrementing from a MemcacheIncrementRequest.
Args:
namespace: A string containing the namespace for the request, if any.
Pass an empty string if there is no namespace.
request: A MemcacheIncrementRequest instance.
Returns:
An integer or long if the offset was successful, None on error.'
| def _internal_increment(self, namespace, request):
| key = request.key()
entry = self._GetKey(namespace, key)
if (entry is None):
if (not request.has_initial_value()):
return None
if (namespace not in self._the_cache):
self._the_cache[namespace] = {}
flags = 0
if request.has_initial_flags():
... |
'Implementation of MemcacheService::Increment().
Args:
request: A MemcacheIncrementRequest.
response: A MemcacheIncrementResponse.'
| def _Dynamic_Increment(self, request, response):
| namespace = request.name_space()
new_value = self._internal_increment(namespace, request)
if (new_value is None):
raise apiproxy_errors.ApplicationError(memcache_service_pb.MemcacheServiceError.UNSPECIFIED_ERROR)
response.set_new_value(new_value)
|
'Implementation of MemcacheService::BatchIncrement().
Args:
request: A MemcacheBatchIncrementRequest.
response: A MemcacheBatchIncrementResponse.'
| def _Dynamic_BatchIncrement(self, request, response):
| namespace = request.name_space()
for request_item in request.item_list():
new_value = self._internal_increment(namespace, request_item)
item = response.add_item()
if (new_value is None):
item.set_increment_status(MemcacheIncrementResponse.NOT_CHANGED)
else:
... |
'Implementation of MemcacheService::FlushAll().
Args:
request: A MemcacheFlushRequest.
response: A MemcacheFlushResponse.'
| def _Dynamic_FlushAll(self, request, response):
| self._the_cache.clear()
self._ResetStats()
|
'Implementation of MemcacheService::Stats().
Args:
request: A MemcacheStatsRequest.
response: A MemcacheStatsResponse.'
| def _Dynamic_Stats(self, request, response):
| stats = response.mutable_stats()
stats.set_hits(self._hits)
stats.set_misses(self._misses)
stats.set_byte_hits(self._byte_hits)
items = 0
total_bytes = 0
for namespace in self._the_cache.itervalues():
items += len(namespace)
for entry in namespace.itervalues():
to... |
'Create a new Client object.
No parameters are required.
Arguments:
servers: Ignored; only for compatibility.
debug: Ignored; only for compatibility.
pickleProtocol: Pickle protocol to use for pickling the object.
pickler: pickle.Pickler sub-class to use for pickling.
unpickler: pickle.Unpickler sub-class to use for un... | def __init__(self, servers=None, debug=0, pickleProtocol=cPickle.HIGHEST_PROTOCOL, pickler=cPickle.Pickler, unpickler=cPickle.Unpickler, pload=None, pid=None, make_sync_call=None, _app_id=None, _num_memcacheg_backends=None):
| self._pickler_factory = pickler
self._unpickler_factory = unpickler
self._pickle_protocol = pickleProtocol
self._persistent_id = pid
self._persistent_load = pload
self._app_id = _app_id
self._num_memcacheg_backends = _num_memcacheg_backends
self._cas_ids = {}
if (_app_id and (not _nu... |
'Clear the remembered CAS ids.'
| def cas_reset(self):
| self._cas_ids.clear()
|
'Internal helper to schedule an asynchronous RPC.
Args:
rpc: None or a UserRPC object.
method: Method name, e.g. \'Get\'.
request: Request protobuf.
response: Response protobuf.
get_result_hook: None or hook function used to process results
(See UserRPC.make_call() for more info).
user_data: None or user data for hook ... | def _make_async_call(self, rpc, method, request, response, get_result_hook, user_data):
| if (rpc is None):
rpc = create_rpc()
assert (rpc.service == 'memcache'), repr(rpc.service)
rpc.make_call(method, request, response, get_result_hook, user_data)
return rpc
|
'Pickles a provided value.'
| def _do_pickle(self, value):
| pickle_data = cStringIO.StringIO()
pickler = self._pickler_factory(pickle_data, protocol=self._pickle_protocol)
if (self._persistent_id is not None):
pickler.persistent_id = self._persistent_id
pickler.dump(value)
return pickle_data.getvalue()
|
'Unpickles a provided value.'
| def _do_unpickle(self, value):
| pickle_data = cStringIO.StringIO(value)
unpickler = self._unpickler_factory(pickle_data)
if (self._persistent_load is not None):
unpickler.persistent_load = self._persistent_load
return unpickler.load()
|
'Populate the app_id and num_memcacheg_backends fields in a message.
Args:
message: A protocol buffer supporting the mutable_override() operation.'
| def _add_app_id(self, message):
| if self._app_id:
app_override = message.mutable_override()
app_override.set_app_id(self._app_id)
app_override.set_num_memcacheg_backends(self._num_memcacheg_backends)
|
'Sets the pool of memcache servers used by the client.
This is purely a compatibility method. In Google App Engine, it\'s a no-op.'
| def set_servers(self, servers):
| pass
|
'Closes all connections to memcache servers.
This is purely a compatibility method. In Google App Engine, it\'s a no-op.'
| def disconnect_all(self):
| pass
|
'Resets all servers to the alive status.
This is purely a compatibility method. In Google App Engine, it\'s a no-op.'
| def forget_dead_hosts(self):
| pass
|
'Logging function for debugging information.
This is purely a compatibility method. In Google App Engine, it\'s a no-op.'
| def debuglog(self):
| pass
|
'Gets memcache statistics for this application.
All of these statistics may reset due to various transient conditions. They
provide the best information available at the time of being called.
Returns:
Dictionary mapping statistic names to associated values. Statistics and
their associated meanings:
hits: Number of cach... | def get_stats(self):
| rpc = self.get_stats_async()
return rpc.get_result()
|
'Async version of get_stats().
Returns:
A UserRPC instance whose get_result() method returns None if
there was a network error, otherwise a dict just like
get_stats() returns.'
| def get_stats_async(self, rpc=None):
| request = MemcacheStatsRequest()
self._add_app_id(request)
response = MemcacheStatsResponse()
return self._make_async_call(rpc, 'Stats', request, response, self.__get_stats_hook, None)
|
'Deletes everything in memcache.
Returns:
True on success, False on RPC or server error.'
| def flush_all(self):
| rpc = self.flush_all_async()
return rpc.get_result()
|
'Async version of flush_all().
Returns:
A UserRPC instance whose get_result() method returns True on
success, False on RPC or server error.'
| def flush_all_async(self, rpc=None):
| request = MemcacheFlushRequest()
self._add_app_id(request)
response = MemcacheFlushResponse()
return self._make_async_call(rpc, 'FlushAll', request, response, self.__flush_all_hook, None)
|
'Looks up a single key in memcache.
If you have multiple items to load, though, it\'s much more efficient
to use get_multi() instead, which loads them in one bulk operation,
reducing the networking latency that\'d otherwise be required to do
many serialized get() operations.
Args:
key: The key in memcache to look up. ... | def get(self, key, namespace=None, for_cas=False):
| if _is_pair(key):
key = key[1]
rpc = self.get_multi_async([key], namespace=namespace, for_cas=for_cas)
results = rpc.get_result()
return results.get(key)
|
'An alias for get(..., for_cas=True).'
| def gets(self, key, namespace=None):
| return self.get(key, namespace=namespace, for_cas=True)
|
'Looks up multiple keys from memcache in one operation.
This is the recommended way to do bulk loads.
Args:
keys: List of keys to look up. Keys may be strings or
tuples of (hash_value, string). Google App Engine
does the sharding and hashing automatically, though, so the hash
value is ignored. To memcache, keys are ... | def get_multi(self, keys, key_prefix='', namespace=None, for_cas=False):
| rpc = self.get_multi_async(keys, key_prefix, namespace, for_cas)
return rpc.get_result()
|
'Async version of get_multi().
Returns:
A UserRPC instance whose get_result() method returns {} if
there was a network error, otherwise a dict just like
get_multi() returns.'
| def get_multi_async(self, keys, key_prefix='', namespace=None, for_cas=False, rpc=None):
| request = MemcacheGetRequest()
self._add_app_id(request)
_add_name_space(request, namespace)
if for_cas:
request.set_for_cas(True)
response = MemcacheGetResponse()
user_key = {}
for key in keys:
request.add_key(_key_string(key, key_prefix, user_key))
return self._make_asy... |
'Deletes a key from memcache.
Args:
key: Key to delete. See docs on Client for detils.
seconds: Optional number of seconds to make deleted items \'locked\'
for \'add\' operations. Value can be a delta from current time (up to
1 month), or an absolute Unix epoch time. Defaults to 0, which means
items can be immediatel... | def delete(self, key, seconds=0, namespace=None):
| rpc = self.delete_multi_async([key], seconds, namespace=namespace)
results = rpc.get_result()
if (not results):
return DELETE_NETWORK_FAILURE
return results[0]
|
'Delete multiple keys at once.
Args:
keys: List of keys to delete.
seconds: Optional number of seconds to make deleted items \'locked\'
for \'add\' operations. Value can be a delta from current time (up to
1 month), or an absolute Unix epoch time. Defaults to 0, which means
items can be immediately added. With or wit... | def delete_multi(self, keys, seconds=0, key_prefix='', namespace=None):
| rpc = self.delete_multi_async(keys, seconds, key_prefix, namespace)
results = rpc.get_result()
return bool(results)
|
'Async version of delete_multi() -- note different return value.
Returns:
A UserRPC instance whose get_result() method returns None if
there was a network error, or a list of status values otherwise,
where each status corresponds to a key and is either
DELETE_SUCCESSFUL, DELETE_ITEM_MISSING, or DELETE_NETWORK_FAILURE
(... | def delete_multi_async(self, keys, seconds=0, key_prefix='', namespace=None, rpc=None):
| if (not isinstance(seconds, (int, long, float))):
raise TypeError('Delete timeout must be a number.')
if (seconds < 0):
raise ValueError('Delete timeout must not be negative.')
request = MemcacheDeleteRequest()
self._add_app_id(request)
_add_name_space(r... |
'Sets a key\'s value, regardless of previous contents in cache.
Unlike add() and replace(), this method always sets (or
overwrites) the value in memcache, regardless of previous
contents.
Args:
key: Key to set. See docs on Client for details.
value: Value to set. Any type. If complex, will be pickled.
time: Optional... | def set(self, key, value, time=0, min_compress_len=0, namespace=None):
| return self._set_with_policy(MemcacheSetRequest.SET, key, value, time=time, namespace=namespace)
|
'Sets a key\'s value, iff item is not already in memcache.
Args:
key: Key to set. See docs on Client for details.
value: Value to set. Any type. If complex, will be pickled.
time: Optional expiration time, either relative number of seconds
from current time (up to 1 month), or an absolute Unix epoch time.
By default... | def add(self, key, value, time=0, min_compress_len=0, namespace=None):
| return self._set_with_policy(MemcacheSetRequest.ADD, key, value, time=time, namespace=namespace)
|
'Replaces a key\'s value, failing if item isn\'t already in memcache.
Args:
key: Key to set. See docs on Client for details.
value: Value to set. Any type. If complex, will be pickled.
time: Optional expiration time, either relative number of seconds
from current time (up to 1 month), or an absolute Unix epoch time.... | def replace(self, key, value, time=0, min_compress_len=0, namespace=None):
| return self._set_with_policy(MemcacheSetRequest.REPLACE, key, value, time=time, namespace=namespace)
|
'Compare-And-Set update.
This requires that the key has previously been successfully
fetched with gets() or get(..., for_cas=True), and that no changes
have been made to the key since that fetch. Typical usage is:
key = ...
client = memcache.Client()
value = client.gets(key) # OR client.get(key, for_cas=True)
<update... | def cas(self, key, value, time=0, min_compress_len=0, namespace=None):
| return self._set_with_policy(MemcacheSetRequest.CAS, key, value, time, namespace)
|
'Sets a single key with a specified policy.
Helper function for set(), add(), and replace().
Args:
policy: One of MemcacheSetRequest.SET, .ADD, .REPLACE or .CAS.
key: Key to add, set, or replace. See docs on Client for details.
value: Value to set.
time: Expiration time, defaulting to 0 (never expiring).
namespace: a... | def _set_with_policy(self, policy, key, value, time=0, namespace=None):
| rpc = self._set_multi_async_with_policy(policy, {key: value}, time, '', namespace)
status_dict = rpc.get_result()
if (not status_dict):
return False
return (status_dict.get(key) == MemcacheSetResponse.STORED)
|
'Set multiple keys with a specified policy.
Helper function for set_multi(), add_multi(), and replace_multi(). This
reduces the network latency of doing many requests in serial.
Args:
policy: One of MemcacheSetRequest.SET, .ADD, .REPLACE or .CAS.
mapping: Dictionary of keys to values. If policy == CAS, the
values mus... | def _set_multi_with_policy(self, policy, mapping, time=0, key_prefix='', namespace=None):
| rpc = self._set_multi_async_with_policy(policy, mapping, time, key_prefix, namespace)
status_dict = rpc.get_result()
(server_keys, user_key) = rpc.user_data
if (not status_dict):
return user_key.values()
unset_list = []
for server_key in server_keys:
key = user_key[server_key]
... |
'Async version of _set_multi_with_policy() -- note different return.
Returns:
A UserRPC instance whose get_result() method returns None if
there was a network error, or a dict mapping (user) keys to
status values otherwise, where each status is one of STORED,
NOT_STORED, ERROR, or EXISTS.'
| def _set_multi_async_with_policy(self, policy, mapping, time=0, key_prefix='', namespace=None, rpc=None):
| if (not isinstance(time, (int, long, float))):
raise TypeError('Expiration must be a number.')
if (time < 0.0):
raise ValueError('Expiration must not be negative.')
request = MemcacheSetRequest()
self._add_app_id(request)
_add_name_space(request, namespace)
... |
'Set multiple keys\' values at once, regardless of previous contents.
Args:
mapping: Dictionary of keys to values.
time: Optional expiration time, either relative number of seconds
from current time (up to 1 month), or an absolute Unix epoch time.
By default, items never expire, though items may be evicted due to
memor... | def set_multi(self, mapping, time=0, key_prefix='', min_compress_len=0, namespace=None):
| return self._set_multi_with_policy(MemcacheSetRequest.SET, mapping, time=time, key_prefix=key_prefix, namespace=namespace)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.