desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Time this request spent in the pending request queue.
Returns:
A float representing the time in seconds that this request was pending.'
| @property
def pending_time(self):
| return (self.__pb.pending_time() / 1000000.0)
|
'The module replica that handled the request as an integer, or None.'
| @property
def replica_index(self):
| if self.__pb.has_replica_index():
return self.__pb.replica_index()
return None
|
'Whether or not this log represents a finished request, as a bool.'
| @property
def finished(self):
| return bool(self.__pb.finished())
|
'Mostly-unique identifier for the instance that handled the request.
Returns:
A string encoding of an instance key if available, or None.'
| @property
def instance_key(self):
| if self.__pb.has_clone_key():
return self.__pb.clone_key()
return None
|
'Logs emitted by the application while serving this request.
Returns:
A list of AppLog objects representing the log lines for this request, or
an empty list if none were emitted or the query did not request them.'
| @property
def app_logs(self):
| if ((not self.__lines) and self.__pb.line_size()):
self.__lines = [AppLog(time=(line.time() / 1000000.0), level=line.level(), message=line.log_message()) for line in self.__pb.line_list()]
return self.__lines
|
'Time log entry was made, in seconds since the Unix epoch, as a float.'
| @property
def time(self):
| return self._time
|
'Level or severity of log, as an int.'
| @property
def level(self):
| return self._level
|
'Application-provided log message, as a string.'
| @property
def message(self):
| return self._message
|
'Initialize event-listener error.'
| def __init__(self, cause):
| if (hasattr(cause, 'args') and cause.args):
Error.__init__(self, *cause.args)
else:
Error.__init__(self, str(cause))
self.cause = cause
|
'Initialize event-listener error.'
| def __init__(self, cause, event):
| EventListenerError.__init__(self, cause)
self.event = event
|
'Validates an URL pattern.'
| def Validate(self, value, unused_key=None):
| if (value is None):
raise validation.MissingAttribute('url must be specified')
if (not isinstance(value, basestring)):
raise validation.ValidationError(("url must be a string, not '%r'" % type(value)))
url_holder = ParsedURL(value)
if url_holder.host_exact:
... |
'Initializes this ParsedURL with an URL pattern value.
Args:
url_pattern: An URL pattern that conforms to the regular expression
Raises:
validation.ValidationError: When url_pattern does not match the required
regular expression.'
| def __init__(self, url_pattern):
| split_matcher = _ValidateMatch(_URL_SPLITTER_RE, url_pattern, ("invalid url '%s'" % url_pattern))
(self.host_pattern, self.path_pattern) = split_matcher.groups()
if self.host_pattern.startswith('*'):
self.host_exact = False
self.host = self.host_pattern[1:]
else:
self.host_... |
'fileno() -> integer
Return the integer file descriptor of the socket.'
| def fileno(self):
| global _GLOBAL_SOCKET_MAP
global _GLOBAL_SOCKET_NEXT_FILENO
if (self._fileno is None):
self._fileno = _GLOBAL_SOCKET_NEXT_FILENO
_GLOBAL_SOCKET_NEXT_FILENO += 1
_GLOBAL_SOCKET_MAP[self._fileno] = self
assert (_GLOBAL_SOCKET_MAP.get(self._fileno) == self), 'fileno mismatch i... |
'bind(address)
Bind the socket to a local address. For IP sockets, the address is a
pair (host, port); the host must refer to the local host. For raw packet
sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])'
| def bind(self, address):
| if (not self._created):
self._CreateSocket(bind_address=address)
return
if (not self._socket_descriptor):
raise error(errno.EBADF, os.strerror(errno.EBADF))
if self._bound:
raise error(errno.EINVAL, os.strerror(errno.EINVAL))
request = remote_socket_service_pb.BindRequest... |
'listen(backlog)
Enable a server to accept connections. The backlog argument must be at
least 1; it specifies the number of unaccepted connection that the system
will allow before refusing new connections.'
| def listen(self, backlog):
| if (not self._created):
self._CreateSocket(bind_address=('', 0))
if (not self._socket_descriptor):
raise error(errno.EBADF, os.strerror(errno.EBADF))
if self._connected:
raise error(errno.EINVAL, os.strerror(errno.EINVAL))
if (self.type != SOCK_STREAM):
raise error(errno.... |
'accept() -> (socket object, address info)
Wait for an incoming connection. Return a new socket representing the
connection, and the address of the client. For IP sockets, the address
info is a pair (hostaddr, port).'
| def accept(self):
| if (not self._created):
self._CreateSocket()
if (not self._socket_descriptor):
raise error(errno.EBADF, os.strerror(errno.EBADF))
if (not self._listen):
raise error(errno.EINVAL, os.strerror(errno.EINVAL))
request = remote_socket_service_pb.AcceptRequest()
request.set_socket_... |
'connect(address)
Connect the socket to a remote address. For IP sockets, the address
is a pair (host, port).'
| def connect(self, address, _hostname_hint=None):
| if (not self._created):
if (self.gettimeout() is None):
self._CreateSocket(address=address, address_hostname_hint=_hostname_hint)
return
else:
self._CreateSocket()
if (not self._socket_descriptor):
raise error(errno.EBADF, os.strerror(errno.EBADF))
... |
'connect_ex(address) -> errno
This is like connect(address), but returns an error code (the errno value)
instead of raising an exception when an error occurs.'
| def connect_ex(self, address):
| try:
self.connect(address)
except error as e:
return e.errno
return 0
|
'getpeername() -> address info
Return the address of the remote endpoint. For IP sockets, the address
info is a pair (hostaddr, port).'
| def getpeername(self):
| if (not self._created):
self._CreateSocket()
if (not self._socket_descriptor):
raise error(errno.EBADF, os.strerror(errno.EBADF))
if (not self._connected):
raise error(errno.ENOTCONN, os.strerror(errno.ENOTCONN))
request = remote_socket_service_pb.GetPeerNameRequest()
request... |
'getsockname() -> address info
Return the address of the local endpoint. For IP sockets, the address
info is a pair (hostaddr, port).'
| def getsockname(self):
| if (not self._created):
self._CreateSocket()
if (not self._socket_descriptor):
raise error(errno.EBADF, os.strerror(errno.EBADF))
request = remote_socket_service_pb.GetSocketNameRequest()
request.set_socket_descriptor(self._socket_descriptor)
reply = remote_socket_service_pb.GetSocke... |
'recv(buffersize[, flags]) -> data
Receive up to buffersize bytes from the socket. For the optional flags
argument, see the Unix manual. When no data is available, block until
at least one byte is available or until the remote end is closed. When
the remote end is closed and all data is read, return the empty string... | def recv(self, buffersize, flags=0):
| return self.recvfrom(buffersize, flags)[0]
|
'recv_into(buffer, [nbytes[, flags]]) -> nbytes_read
A version of recv() that stores its data into a buffer rather than
creating a new string. Receive up to buffersize bytes from the socket.
If buffersize is not specified (or 0), receive up to the size available
in the given buffer.
See recv() for documentation about ... | def recv_into(self, buf, nbytes=0, flags=0):
| raise NotImplementedError()
|
'recvfrom(buffersize[, flags]) -> (data, address info)
Like recv(buffersize, flags) but also return the sender\'s address info.'
| def recvfrom(self, buffersize, flags=0):
| if (not self._created):
self._CreateSocket()
if (not self._socket_descriptor):
raise error(errno.EBADF, os.strerror(errno.EBADF))
request = remote_socket_service_pb.ReceiveRequest()
request.set_socket_descriptor(self._socket_descriptor)
request.set_data_size(buffersize)
request.s... |
'recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)
Like recv_into(buffer[, nbytes[, flags]]) but also return the
sender\'s address info.'
| def recvfrom_into(self, buffer, nbytes=0, flags=0):
| raise NotImplementedError()
|
'send(data[, flags]) -> count
Send a data string to the socket. For the optional flags
argument, see the Unix manual. Return the number of bytes
sent; this may be less than len(data) if the network is busy.'
| def send(self, data, flags=0):
| return self.sendto(data, flags, None)
|
'sendall(data[, flags])
Send a data string to the socket. For the optional flags
argument, see the Unix manual. This calls send() repeatedly
until all data is sent. If an error occurs, it\'s impossible
to tell how much data has been sent.'
| def sendall(self, data, flags=0):
| offset = 0
while (offset < len(data)):
offset += self.sendto(data[offset:], flags, None)
|
'sendto(data[, flags], address) -> count
Like send(data, flags) but allows specifying the destination address.
For IP sockets, the address is a pair (hostaddr, port).'
| def sendto(self, data, *args):
| if (len(args) == 1):
(flags, address) = (0, args[0])
elif (len(args) == 2):
(flags, address) = args
if (not self._created):
self._CreateSocket()
if (not self._socket_descriptor):
raise error(errno.EBADF, os.strerror(errno.EBADF))
if self._shutdown_write:
raise... |
'setblocking(flag)
Set the socket to blocking (flag is true) or non-blocking (false).
setblocking(True) is equivalent to settimeout(None);
setblocking(False) is equivalent to settimeout(0.0).'
| def setblocking(self, block):
| if block:
self._timeout = (-1.0)
else:
self._timeout = 0.0
|
'settimeout(timeout)
Set a timeout on socket operations. \'timeout\' can be a float,
giving in seconds, or None. Setting a timeout of None disables
the timeout feature and is equivalent to setblocking(1).
Setting a timeout of zero is the same as setblocking(0).'
| def settimeout(self, timeout):
| if (timeout is None):
self._timeout = (-1.0)
else:
try:
self._timeout = (0.0 + timeout)
except:
raise TypeError('a float is required')
if (self._timeout < 0.0):
raise ValueError('Timeout value out of range')
|
'gettimeout() -> timeout
Returns the timeout in floating seconds associated with socket
operations. A timeout of None indicates that timeouts on socket
operations are disabled.'
| def gettimeout(self):
| if (self._timeout < 0.0):
return None
return self._timeout
|
'setsockopt(level, option, value)
Set a socket option. See the Unix manual for level and option.
The value argument can either be an integer or a string.'
| def setsockopt(self, level, option, value):
| if (not self._created):
self._setsockopt.append((level, option, value))
self._CreateSocket()
return
if (not self._socket_descriptor):
raise error(errno.EBADF, os.strerror(errno.EBADF))
request = remote_socket_service_pb.SetSocketOptionsRequest()
request.set_socket_descrip... |
'getsockopt(level, option[, buffersize]) -> value
Get a socket option. See the Unix manual for level and option.
If a nonzero buffersize argument is given, the return value is a
string of that length; otherwise it is an integer.'
| def getsockopt(self, level, option, buffersize=0):
| if (not self._created):
self._CreateSocket()
if (not self._socket_descriptor):
raise error(errno.EBADF, os.strerror(errno.EBADF))
request = remote_socket_service_pb.GetSocketOptionsRequest()
request.set_socket_descriptor(self._socket_descriptor)
o = request.add_options()
o.set_le... |
'shutdown(flag)
Shut down the reading side of the socket (flag == SHUT_RD), the writing side
of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).'
| def shutdown(self, flag):
| if (not (flag in (SHUT_RD, SHUT_WR, SHUT_RDWR))):
raise error(errno.EINVAL, os.strerror(errno.EINVAL))
if (not self._created):
self._CreateSocket()
if (not self._socket_descriptor):
raise error(errno.EBADF, os.strerror(errno.EBADF))
if ((not self._connected) or (self._shutdown_re... |
'close()
Close the socket. It cannot be used after this call.'
| def close(self):
| self._created = True
if (not self._socket_descriptor):
return
request = remote_socket_service_pb.CloseRequest()
request.set_socket_descriptor(self._socket_descriptor)
reply = remote_socket_service_pb.CloseReply()
try:
apiproxy_stub_map.MakeSyncCall('remote_socket', 'Close', reque... |
'Initializer.
Args:
log: where to log messages
service_name: service name expected for all calls
get_time: Used for testing. Function that works like time.time().'
| def __init__(self, service_name='remote_socket', get_time=time.time):
| super(RemoteSocketServiceStub, self).__init__(service_name)
self._descriptor_to_socket_state = {}
self._time = get_time
|
'Converts an AddressPort proto into a python (addrstr, port) tuple.'
| def _AddressPortTupleFromProto(self, family, ap_proto):
| try:
addr = _remote_socket_addr.inet_ntop(self._TRANSLATED_AF_MAP[family], ap_proto.packed_address())
except ValueError:
raise apiproxy_errors.ApplicationError(remote_socket_service_pb.RemoteSocketServiceError.INVALID_REQUEST, 'Invalid Address.')
return (addr, ap_proto.port())
|
'Converts a python (addrstr, port) tuple into an AddressPort proto.'
| def _AddressPortTupleToProto(self, family, ap_tuple, ap_proto):
| ap_proto.set_packed_address(_remote_socket_addr.inet_pton(self._TRANSLATED_AF_MAP[family], ap_tuple[0]))
ap_proto.set_port(ap_tuple[1])
|
'Initializer.
Args:
log: A logger, used for dependency injection.
service_name: Service name expected for all calls.
time_func: function to get the current time in seconds.
request_data: A request_info.RequestInfo instance. If None, a
request_info._LocalRequestInfo instance will be used.'
| def __init__(self, log=logging.debug, service_name='channel', time_func=time.time, request_data=None):
| apiproxy_stub.APIProxyStub.__init__(self, service_name, request_data=request_data)
self._log = log
self._time_func = time_func
self._connected_channel_messages = {}
self._add_event = None
self._update_event = None
|
'Implementation of channel.send_message.
Queues a message to be retrieved by the client when it polls.
Args:
request: A SendMessageRequest.
response: A VoidProto.'
| def _Dynamic_SendChannelMessage(self, request, response):
| client_id = request.application_key()
if (not request.message()):
raise apiproxy_errors.ApplicationError(channel_service_pb.ChannelServiceError.BAD_MESSAGE)
if (client_id in self._connected_channel_messages):
self._log('Sending a message (%s) to channel with key (%s)'... |
'Returns the client id from a given token.
Args:
token: String representing an instance of a client connection to a
client id, returned by CreateChannel.
Returns:
String representing the client id used to create this token,
or None if this token is incorrectly formed and doesn\'t map to a
client id.'
| def client_id_from_token(self, token):
| pieces = token.split('-', 2)
if (len(pieces) == 3):
return pieces[2]
else:
return None
|
'Returns the pending messages for a given channel.
Args:
token: String representing the channel. Note that this is the token
returned by CreateChannel, not the client id.
Returns:
List of messages, or None if the channel doesn\'t exist. The messages are
strings.'
| def get_channel_messages(self, token):
| self._log(('Received request for messages for channel: ' + token))
client_id = self.client_id_from_token(token)
if (client_id in self._connected_channel_messages):
return self._connected_channel_messages[client_id]
return None
|
'Checks to see if the given channel has any pending messages.
Args:
token: String representing the channel. Note that this is the token
returned by CreateChannel, not the client id.
Returns:
True if the channel exists and has pending messages.'
| def has_channel_messages(self, token):
| client_id = self.client_id_from_token(token)
has_messages = ((client_id in self._connected_channel_messages) and bool(self._connected_channel_messages[client_id]))
self._log('Checking for messages on channel (%s) (%s)', token, has_messages)
return has_messages
|
'Returns and clears the first message from the message queue.
Args:
token: String representing the channel. Note that this is the token
returned by CreateChannel, not the client id.
Returns:
The first message in the queue, or None if no messages.'
| def pop_first_message(self, token):
| if self.has_channel_messages(token):
client_id = self.client_id_from_token(token)
self._log('Popping first message of queue for channel (%s)', token)
return self._connected_channel_messages[client_id].pop(0)
return None
|
'Clears all messages from the channel.
Args:
token: String representing the channel. Note that this is the token
returned by CreateChannel, not the client id.'
| def clear_channel_messages(self, token):
| client_id = self.client_id_from_token(token)
if client_id:
self._log((('Clearing messages on channel (' + client_id) + ')'))
if (client_id in self._connected_channel_messages):
self._connected_channel_messages[client_id] = []
else:
self._log((('Ignoring cle... |
'Tell the application that the client has connected.'
| def connect_channel_event(self, client_id):
| return (self.ChannelPresenceSocket('connected/', client_id), (ChannelServiceStub.XMPP_PUBLIC_IP, ChannelServiceStub.XMPP_PUBLIC_PORT))
|
'Add an event to make a POST to the /_ah/channel/connect path.
In production, the BuzzBot will make an HttpOverRpc call to the above path
when it receives a presence stanza. We simulate the same thing here by using
the dev_appserver\'s eventing architecture to make a request. Note that this
request will be blocked in t... | def add_connect_event(self, client_id):
| def DefineSendConnectPresenceCallback(client_id):
return (lambda : self.connect_channel_event(client_id))
self._add_event(0, DefineSendConnectPresenceCallback(client_id), 'channel-connect', client_id)
|
'Removes the channel from the list of connected channels.'
| def disconnect_channel_event(self, client_id):
| self._log('Removing channel %s', client_id)
if (client_id in self._connected_channel_messages):
del self._connected_channel_messages[client_id]
return (self.ChannelPresenceSocket('disconnected/', client_id), (ChannelServiceStub.XMPP_PUBLIC_IP, ChannelServiceStub.XMPP_PUBLIC_PORT))
|
'Add an event to notify the app if a client has disconnected.
See the comments in add_connect_event above.'
| def add_disconnect_event(self, client_id):
| timeout = (self._time_func() + ChannelServiceStub.CHANNEL_TIMEOUT_SECONDS)
def DefineDisconnectCallback(client_id):
return (lambda : self.disconnect_channel_event(client_id))
self._add_event(timeout, DefineDisconnectCallback(client_id), 'channel-disconnect', client_id)
|
'Marks the channel identified by the token (token) as connected.'
| def connect_channel(self, token):
| client_id = self.client_id_from_token(token)
if (client_id in self._connected_channel_messages):
if self._update_event:
timeout = (self._time_func() + ChannelServiceStub.CHANNEL_TIMEOUT_SECONDS)
self._update_event('channel-disconnect', client_id, timeout)
return
self.... |
'Constructor.
Args:
modname: The module name to be imported.
Note: the actual import of this module is deferred until the first
time a configuration value is requested through attribute access
on a ConfigHandle instance.'
| def __init__(self, modname):
| self._modname = modname
self._registrations = {}
self._module = None
self._lock = threading.RLock()
|
'Register a set of configuration names.
Args:
prefix: A shared prefix for the configuration names being registered.
If the prefix doesn\'t end in \'_\', that character is appended.
mapping: A dict mapping suffix strings to default values.
Returns:
A ConfigHandle instance.
It\'s okay to re-register the same prefix: the ... | def register(self, prefix, mapping):
| if (not prefix.endswith('_')):
prefix += '_'
self._lock.acquire()
try:
handle = self._registrations.get(prefix)
if (handle is None):
handle = ConfigHandle(prefix, self)
self._registrations[prefix] = handle
finally:
self._lock.release()
handle._... |
'Attempt to import the config module, if not already imported.
This function always sets self._module to a value unequal
to None: either the imported module (if imported successfully), or
a dummy object() instance (if an ImportError was raised). Other
exceptions are *not* caught.
When a dummy instance is used, it is a... | def initialize(self, import_func=__import__):
| self._lock.acquire()
try:
if ((self._module is not None) and (self._module is sys.modules.get(self._modname))):
return
try:
import_func(self._modname)
except ImportError as err:
if (str(err) != ('No module named %s' % self._modname)):
... |
'Drops the imported config module.
If the config module has not been imported then this is a no-op.'
| def reset(self):
| self._lock.acquire()
try:
if (self._module is None):
return
self._module = None
handles = self._registrations.values()
finally:
self._lock.release()
for handle in handles:
handle._clear_cache()
|
'Generate (key, value) pairs from the config module matching prefix.
Args:
prefix: A prefix string ending in \'_\', e.g. \'mylib_\'.
Yields:
(key, value) pairs where key is the configuration name with
prefix removed, and value is the corresponding value.'
| def _pairs(self, prefix):
| self._lock.acquire()
try:
mapping = getattr(self._module, '__dict__', None)
if (not mapping):
return
items = mapping.items()
finally:
self._lock.release()
nskip = len(prefix)
for (key, value) in items:
if key.startswith(prefix):
(yield ... |
'Print info about all registrations to stdout.'
| def _dump(self):
| self.initialize()
handles = []
self._lock.acquire()
try:
if (not hasattr(self._module, '__dict__')):
print ('Module %s.py does not exist.' % self._modname)
elif (not self._registrations):
print ('No registrations for %s.py.' % self._modname)
... |
'Constructor.
Args:
prefix: A shared prefix for the configuration names being registered.
It *must* end in \'_\'. (This is enforced by LibConfigRegistry.)
registry: A LibConfigRegistry instance.'
| def __init__(self, prefix, registry):
| assert prefix.endswith('_')
self._prefix = prefix
self._defaults = {}
self._overrides = {}
self._registry = registry
self._lock = threading.RLock()
|
'Update the default mappings.
Args:
mapping: A dict mapping suffix strings to default values.'
| def _update_defaults(self, mapping):
| self._lock.acquire()
try:
for (key, value) in mapping.iteritems():
if (key.startswith('__') and key.endswith('__')):
continue
self._defaults[key] = value
if self._initialized:
self._update_configs()
finally:
self._lock.release()
|
'Update the configuration values.
This clears the cached values, initializes the registry, and loads
the configuration values from the config module.'
| def _update_configs(self):
| self._lock.acquire()
try:
if self._initialized:
self._clear_cache()
self._registry.initialize()
for (key, value) in self._registry._pairs(self._prefix):
if (key not in self._defaults):
logging.warn('Configuration "%s" not recognized', (sel... |
'Clear the cached values.'
| def _clear_cache(self):
| self._lock.acquire()
try:
self._initialized = False
for key in self._defaults:
self._overrides.pop(key, None)
try:
delattr(self, key)
except AttributeError:
pass
finally:
self._lock.release()
|
'Print info about this set of registrations to stdout.'
| def _dump(self):
| self._lock.acquire()
try:
print ('Prefix %s:' % self._prefix)
if self._overrides:
print ' Overrides:'
for key in sorted(self._overrides):
print (' %s = %r' % (key, self._overrides[key]))
else:
print ' ... |
'Dynamic attribute access.
Args:
suffix: The attribute name.
Returns:
A configuration values.
Raises:
AttributeError if the suffix is not a registered suffix.
The first time an attribute is referenced, this method is invoked.
The value returned taken either from the config module or from the
registered default.'
| def __getattr__(self, suffix):
| self._lock.acquire()
try:
if (not self._initialized):
self._update_configs()
if (suffix in self._overrides):
value = self._overrides[suffix]
elif (suffix in self._defaults):
value = self._defaults[suffix]
else:
raise AttributeError(... |
'Create a _StoredEntity object and store an entity.
Args:
entity: entity_pb.EntityProto to store.'
| def __init__(self, entity):
| self.protobuf = entity
self.encoded_protobuf = entity.Encode()
|
'Perform a query on this pseudo-kind.
Args:
query: the original datastore_pb.Query.
filters: the filters from query.
orders: the orders from query.
Returns:
(results, remaining_filters, remaining_orders)
results is a list of entity_pb.EntityProto
remaining_filters and remaining_orders are the filters and orders that
sh... | def Query(self, query, filters, orders):
| kind_range = datastore_stub_util.ParseKindQuery(query, filters, orders)
app_namespace_str = datastore_types.EncodeAppIdNamespace(query.app(), query.name_space())
kinds = []
for (app_namespace, kind) in self._stub._GetAllEntities():
if (app_namespace != app_namespace_str):
continue
... |
'Perform a query on this pseudo-kind.
Args:
query: the original datastore_pb.Query.
filters: the filters from query.
orders: the orders from query.
Returns:
(results, remaining_filters, remaining_orders)
results is a list of entity_pb.EntityProto
remaining_filters and remaining_orders are the filters and orders that
sh... | def Query(self, query, filters, orders):
| property_range = datastore_stub_util.ParsePropertyQuery(query, filters, orders)
keys_only = query.keys_only()
app_namespace_str = datastore_types.EncodeAppIdNamespace(query.app(), query.name_space())
properties = []
if keys_only:
usekey = '__property__keys'
else:
usekey = '__prop... |
'Perform a query on this pseudo-kind.
Args:
query: the original datastore_pb.Query.
filters: the filters from query.
orders: the orders from query.
Returns:
(results, remaining_filters, remaining_orders)
results is a list of entity_pb.EntityProto
remaining_filters and remaining_orders are the filters and orders that
sh... | def Query(self, query, filters, orders):
| namespace_range = datastore_stub_util.ParseNamespaceQuery(query, filters, orders)
app_str = query.app()
namespaces = set()
for (app_namespace, _) in self._stub._GetAllEntities():
(app_id, namespace) = datastore_types.DecodeAppIdNamespace(app_namespace)
if ((app_id == app_str) and namespa... |
'Constructor.
Initializes and loads the datastore from the backing files, if they exist.
Args:
app_id: string
datastore_file: string, stores all entities across sessions. Use None
not to use a file.
history_file: DEPRECATED. No-op.
require_indexes: bool, default False. If True, composite indexes must
exist in index.y... | def __init__(self, app_id, datastore_file, history_file=None, require_indexes=False, service_name='datastore_v3', trusted=False, consistency_policy=None, save_changes=True, root_path=None, use_atexit=True, auto_id_policy=datastore_stub_util.SEQUENTIAL):
| self.__datastore_file = datastore_file
self.__save_changes = save_changes
self.__entities_by_kind = collections.defaultdict(dict)
self.__entities_by_group = collections.defaultdict(dict)
self.__entities_lock = threading.Lock()
self.__schema_cache = {}
self.__id_counters = {datastore_stub_uti... |
'Clears the datastore by deleting all currently stored entities and
queries.'
| def Clear(self):
| self.__entities_lock.acquire()
try:
datastore_stub_util.BaseDatastore.Clear(self)
datastore_stub_util.DatastoreStub.Clear(self)
self.__entities_by_kind = collections.defaultdict(dict)
self.__entities_by_group = collections.defaultdict(dict)
self.__schema_cache = {}
fi... |
'Get all entities.
Returns:
Map from kind to _StoredEntity() list. Do not modify directly.'
| def _GetAllEntities(self):
| return self.__entities_by_kind
|
'Get keys to self.__entities_by_* from the given key.
Example usage:
app_kind, eg_k, k = self._GetEntityLocation(key)
self.__entities_by_kind[app_kind][k]
self.__entities_by_entity_group[eg_k][k]
Args:
key: entity_pb.Reference
Returns:
Tuple (by_kind key, by_entity_group key, entity key)'
| def _GetEntityLocation(self, key):
| app_ns = datastore_types.EncodeAppIdNamespace(key.app(), key.name_space())
kind = _FinalElement(key).type()
entity_group = datastore_stub_util._GetEntityGroup(key)
eg_k = datastore_types.ReferenceToKeyValue(entity_group)
k = datastore_types.ReferenceToKeyValue(key)
return ((app_ns, kind), eg_k, ... |
'Store the given entity.
Any needed locking should be managed by the caller.
Args:
entity: The entity_pb.EntityProto to store.
insert: If we should check for existence.'
| def _StoreEntity(self, entity, insert=False):
| (app_kind, eg_k, k) = self._GetEntityLocation(entity.key())
assert ((not insert) or (k not in self.__entities_by_kind[app_kind]))
self.__entities_by_kind[app_kind][k] = _StoredEntity(entity)
self.__entities_by_group[eg_k][k] = entity
if (app_kind in self.__schema_cache):
del self.__schema_ca... |
'Reads the datastore and history files into memory.
The in-memory query history is cleared, but the datastore is *not*
cleared; the entities in the files are merged into the entities in memory.
If you want them to overwrite the in-memory datastore, call Clear() before
calling Read().
If the datastore file contains an e... | def Read(self):
| if (self.__datastore_file and (self.__datastore_file != '/dev/null')):
for encoded_entity in self.__ReadPickled(self.__datastore_file):
try:
entity = entity_pb.EntityProto(encoded_entity)
except self.READ_PB_EXCEPTIONS as e:
raise apiproxy_errors.Appli... |
'Writes out the datastore and history files.
Be careful! If the files already exist, this method overwrites them!'
| def Write(self):
| super(DatastoreFileStub, self).Write()
self.__WriteDatastore()
|
'Writes out the datastore file. Be careful! If the file already exists,
this method overwrites it!'
| def __WriteDatastore(self):
| if self.__IsSaveable():
encoded = []
for kind_dict in self.__entities_by_kind.values():
encoded.extend((entity.encoded_protobuf for entity in kind_dict.values()))
self.__WritePickled(encoded, self.__datastore_file)
|
'Reads a pickled object from the given file and returns it.'
| def __ReadPickled(self, filename):
| self.__file_lock.acquire()
try:
if (filename and (filename != '/dev/null') and os.path.isfile(filename) and (os.stat(filename).st_size > 0)):
return pickle.load(open(filename, 'rb'))
else:
logging.warning('Could not read datastore data from %s', filename... |
'Pickles the object and writes it to the given file.'
| def __WritePickled(self, obj, filename):
| if ((not filename) or (filename == '/dev/null') or (not obj)):
return
(descriptor, tmp_filename) = tempfile.mkstemp(dir=os.path.dirname(filename))
tmpfile = os.fdopen(descriptor, 'wb')
pickler = pickle.Pickler(tmpfile, protocol=1)
pickler.fast = True
pickler.dump(obj)
tmpfile.close()... |
'The main RPC entry point. service must be \'datastore_v3\'.'
| def MakeSyncCall(self, service, call, request, response, request_id=None):
| self.assertPbIsInitialized(request)
super(DatastoreFileStub, self).MakeSyncCall(service, call, request, response, request_id)
self.assertPbIsInitialized(response)
|
'Raises an exception if the given PB is not initialized and valid.'
| def assertPbIsInitialized(self, pb):
| explanation = []
assert pb.IsInitialized(explanation), explanation
pb.Encode()
|
'Set the ID counter for id_space to value.'
| def _SetIdCounter(self, id_space, value):
| self.__id_counters[id_space] = value
|
'Return current value of ID counter for id_space.'
| def _IdCounter(self, id_space):
| return self.__id_counters[id_space]
|
'Infer ID space and advance corresponding counter.'
| def _SetMaxId(self, max_id):
| (count, id_space) = datastore_stub_util.IdToCounter(max_id)
if (count >= self._IdCounter(id_space)):
self._SetIdCounter(id_space, (count + 1))
|
'Setter for \'class\', since an attribute reference is an error.'
| def set_class(self, Class):
| self.Set(CLASS, Class)
|
'Accessor for \'class\', since an attribute reference is an error.'
| def get_class(self):
| return self.Get(CLASS)
|
'Returns a sorted dictionary representing the backend entry.'
| def ToDict(self):
| self.ParseOptions().WriteOptions()
result = super(BackendEntry, self).ToDict()
return SortedDict([NAME, CLASS, INSTANCES, START, OPTIONS, MAX_CONCURRENT_REQUESTS, STATE], result)
|
'Parses the \'options\' field and sets appropriate fields.'
| def ParseOptions(self):
| if self.options:
options = [option.strip() for option in self.options.split(',')]
else:
options = []
for option in options:
if (option not in VALID_OPTIONS):
raise BadConfig('Unrecognized option: %s', option)
self.public = (PUBLIC in options)
self.dynamic = ... |
'Writes the \'options\' field based on other settings.'
| def WriteOptions(self):
| options = []
if self.public:
options.append('public')
if self.dynamic:
options.append('dynamic')
if self.failfast:
options.append('failfast')
if options:
self.options = ', '.join(options)
else:
self.options = None
return self
|
'Constructor.
Args:
host: Host of SMTP mail server.
port: Port of SMTP mail server.
user: Sending user of SMTP mail.
password: SMTP password.
enable_sendmail: Whether sendmail enabled or not.
show_mail_body: Whether to show mail body in log.
service_name: Service name expected for all calls.
allow_tls: Allow TLS suppor... | def __init__(self, host=None, port=25, user='', password='', enable_sendmail=False, show_mail_body=False, service_name='mail', allow_tls=False):
| super(MailServiceStub, self).__init__(service_name, max_request_size=MAX_REQUEST_SIZE)
self._smtp_host = host
self._smtp_port = port
self._smtp_user = user
self._smtp_password = password
self._enable_sendmail = enable_sendmail
self._show_mail_body = show_mail_body
self._allow_tls = allow... |
'Generate a list of log messages representing sent mail.
Args:
message: Message to write to log.
log: Log function of type string -> None'
| def _GenerateLog(self, method, message, log):
| log_message = []
log_message.append(('MailService.%s' % method))
log_message.append((' From: %s' % message.sender()))
for address in message.to_list():
log_message.append((' To: %s' % address))
for address in message.cc_list():
log_message.append((' Cc: ... |
'Cache a message that were sent for later inspection.
Args:
message: Message to cache.'
| @apiproxy_stub.Synchronized
def _CacheMessage(self, message):
| self._cached_messages.append(message)
|
'Get a list of mail messages sent via the Mail API.
Args:
to: A regular expression that at least one recipient must match.
sender: A regular expression that the sender must match.
subject: A regular expression that the message subject must match.
body: A regular expression that the text body must match.
html: A regular... | @apiproxy_stub.Synchronized
def get_sent_messages(self, to=None, sender=None, subject=None, body=None, html=None):
| messages = self._cached_messages
def recipient_matches(recipient):
return re.search(to, recipient)
if to:
messages = [m for m in messages if filter(recipient_matches, m.to_list())]
if sender:
messages = [m for m in messages if re.search(sender, m.sender())]
if subject:
... |
'Send MIME message via SMTP.
Connects to SMTP server and sends MIME message. If user is supplied
will try to login to that server to send as authenticated. Does not
currently support encryption.
Args:
mime_message: MimeMessage to send. Create using ToMIMEMessage.
smtp_lib: Class of SMTP library. Used for dependency... | def _SendSMTP(self, mime_message, smtp_lib=smtplib.SMTP):
| smtp = smtp_lib()
try:
smtp.connect(self._smtp_host, self._smtp_port)
smtp.ehlo_or_helo_if_needed()
if (self._allow_tls and smtp.has_extn('STARTTLS')):
smtp.starttls()
smtp.ehlo()
if self._smtp_user:
smtp.login(self._smtp_user, self._smtp_passw... |
'Send MIME message via sendmail, if exists on computer.
Attempts to send email via sendmail. Any IO failure, including
the program not being found is ignored.
Args:
mime_message: MimeMessage to send. Create using ToMIMEMessage.
popen: popen function to create a new sub-process.'
| def _SendSendmail(self, mime_message, popen=subprocess.Popen, sendmail_command='sendmail'):
| try:
tos = []
for to in ('To', 'Cc', 'Bcc'):
if mime_message[to]:
tos.extend((("'%s'" % addr.strip().replace("'", "'\\''")) for addr in unicode(mime_message[to]).split(',')))
command = ('%s %s' % ('/root/appscale/scripts/sendmail', ' '.join(tos)))
tr... |
'Implementation of MailServer::Send().
Logs email message. Contents of attachments are not shown, only
their sizes. If SMTP is configured, will send via SMTP, else
will use Sendmail if it is installed.
Args:
request: The message to send, a SendMailRequest.
response: The send response, a SendMailResponse.
log: Log fun... | def _Send(self, request, response, log=logging.info, smtp_lib=smtplib.SMTP, popen=subprocess.Popen, sendmail_command='sendmail'):
| self._CacheMessage(request)
self._GenerateLog('Send', request, log)
if (self._smtp_host and self._enable_sendmail):
log('Both SMTP and sendmail are enabled. Ignoring sendmail.')
import email
mime_message = mail.MailMessageToMIMEMessage(request)
_Base64EncodeAttac... |
'Implementation of MailServer::SendToAdmins().
Logs email message. Contents of attachments are not shown, only
their sizes.
Given the difficulty of determining who the actual sender
is, Sendmail and SMTP are disabled for this action.
Args:
request: The message to send, a SendMailRequest.
response: The send response, a... | def _SendToAdmins(self, request, response, log=logging.info):
| self._GenerateLog('SendToAdmins', request, log)
if (self._smtp_host and self._enable_sendmail):
log('Both SMTP and sendmail are enabled. Ignoring sendmail.')
|
'Constructor.
Args:
blob_key: The blob_key that is believed to be invalid. May be None if the
BlobKey is unknown.'
| def __init__(self, blob_key=None):
| self._blob_key = blob_key
|
'Returns a string representation of this Error.'
| def __str__(self):
| if self._blob_key:
return ('InvalidBlobKeyError: %s' % repr(self._blob_key))
else:
return 'InvalidBlobKeyError'
|
'Constructor.
Only one of image_data, blob_key or filename can be specified.
Args:
image_data: str, image data in string form.
blob_key: BlobKey, BlobInfo, str, or unicode representation of BlobKey of
blob containing the image data.
filename: str, the filename of a Google Storage file containing the
image data. Must be... | def __init__(self, image_data=None, blob_key=None, filename=None):
| if ((not image_data) and (not blob_key) and (not filename)):
raise NotImageError('Empty image data.')
if (image_data and (blob_key or filename)):
raise NotImageError('Can only take one of image, blob key or filename.')
if (blob_key and filename):
rais... |
'Ensure some simple limits on the number of transforms allowed.
Raises:
BadRequestError if MAX_TRANSFORMS_PER_REQUEST transforms have already been
requested for this image'
| def _check_transform_limits(self):
| if (len(self._transforms) >= MAX_TRANSFORMS_PER_REQUEST):
raise BadRequestError(('%d transforms have already been requested on this image.' % MAX_TRANSFORMS_PER_REQUEST))
|
'Updates the width and height fields of the image.
Raises:
NotImageError if the image data is not an image.
BadImageError if the image data is corrupt.'
| def _update_dimensions(self):
| if (not self._image_data):
raise NotImageError('Dimensions unavailable for blob key input')
size = len(self._image_data)
if ((size >= 6) and self._image_data.startswith('GIF')):
self._update_gif_dimensions()
self._format = GIF
elif ((size >= 8) and self._image_data... |
'Updates the width and height fields of the gif image.
Raises:
BadImageError if the image string is not a valid gif image.'
| def _update_gif_dimensions(self):
| size = len(self._image_data)
if (size >= 10):
(self._width, self._height) = struct.unpack('<HH', self._image_data[6:10])
else:
raise BadImageError('Corrupt GIF format')
|
'Updates the width and height fields of the png image.
Raises:
BadImageError if the image string is not a valid png image.'
| def _update_png_dimensions(self):
| size = len(self._image_data)
if ((size >= 24) and (self._image_data[12:16] == 'IHDR')):
(self._width, self._height) = struct.unpack('>II', self._image_data[16:24])
else:
raise BadImageError('Corrupt PNG format')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.