desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Async version of set_multi() -- note different return value. Returns: See _set_multi_async_with_policy().'
def set_multi_async(self, mapping, time=0, key_prefix='', min_compress_len=0, namespace=None, rpc=None):
return self._set_multi_async_with_policy(MemcacheSetRequest.SET, mapping, time=time, key_prefix=key_prefix, namespace=namespace, rpc=rpc)
'Set multiple keys\' values iff items are not already in memcache. 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 memory p...
def add_multi(self, mapping, time=0, key_prefix='', min_compress_len=0, namespace=None):
return self._set_multi_with_policy(MemcacheSetRequest.ADD, mapping, time=time, key_prefix=key_prefix, namespace=namespace)
'Async version of add_multi() -- note different return value. Returns: See _set_multi_async_with_policy().'
def add_multi_async(self, mapping, time=0, key_prefix='', min_compress_len=0, namespace=None, rpc=None):
return self._set_multi_async_with_policy(MemcacheSetRequest.ADD, mapping, time=time, key_prefix=key_prefix, namespace=namespace, rpc=rpc)
'Replace multiple keys\' values, failing if the items aren\'t in memcache. 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 ...
def replace_multi(self, mapping, time=0, key_prefix='', min_compress_len=0, namespace=None):
return self._set_multi_with_policy(MemcacheSetRequest.REPLACE, mapping, time=time, key_prefix=key_prefix, namespace=namespace)
'Async version of replace_multi() -- note different return value. Returns: See _set_multi_async_with_policy().'
def replace_multi_async(self, mapping, time=0, key_prefix='', min_compress_len=0, namespace=None, rpc=None):
return self._set_multi_async_with_policy(MemcacheSetRequest.REPLACE, mapping, time=time, key_prefix=key_prefix, namespace=namespace, rpc=rpc)
'Compare-And-Set update for multiple keys. See cas() docstring for an explanation. 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...
def cas_multi(self, mapping, time=0, key_prefix='', min_compress_len=0, namespace=None):
return self._set_multi_with_policy(MemcacheSetRequest.CAS, mapping, time=time, key_prefix=key_prefix, namespace=namespace)
'Async version of cas_multi() -- note different return value. Returns: See _set_multi_async_with_policy().'
def cas_multi_async(self, mapping, time=0, key_prefix='', min_compress_len=0, namespace=None, rpc=None):
return self._set_multi_async_with_policy(MemcacheSetRequest.CAS, mapping, time=time, key_prefix=key_prefix, namespace=namespace, rpc=rpc)
'Atomically increments a key\'s value. Internally, the value is a unsigned 64-bit integer. Memcache doesn\'t check 64-bit overflows. The value, if too large, will wrap around. Unless an initial_value is specified, the key must already exist in the cache to be incremented. To initialize a counter, either specify init...
def incr(self, key, delta=1, namespace=None, initial_value=None):
return self._incrdecr(key, False, delta, namespace=namespace, initial_value=initial_value)
'Async version of incr(). Returns: A UserRPC instance whose get_result() method returns the same kind of value as incr() returns.'
def incr_async(self, key, delta=1, namespace=None, initial_value=None, rpc=None):
return self._incrdecr_async(key, False, delta, namespace=namespace, initial_value=initial_value, rpc=rpc)
'Atomically decrements a key\'s value. Internally, the value is a unsigned 64-bit integer. Memcache caps decrementing below zero to zero. The key must already exist in the cache to be decremented. See docs on incr() for details. Args: key: Key to decrement. If an iterable collection, each one of the keys will be offs...
def decr(self, key, delta=1, namespace=None, initial_value=None):
return self._incrdecr(key, True, delta, namespace=namespace, initial_value=initial_value)
'Async version of decr(). Returns: A UserRPC instance whose get_result() method returns the same kind of value as decr() returns.'
def decr_async(self, key, delta=1, namespace=None, initial_value=None, rpc=None):
return self._incrdecr_async(key, True, delta, namespace=namespace, initial_value=initial_value, rpc=rpc)
'Increment or decrement a key by a provided delta. Args: key: Key to increment or decrement. If an iterable collection, each one of the keys will be offset. is_negative: Boolean, if this is a decrement. delta: Non-negative integer amount (int or long) to increment or decrement by. namespace: a string specifying an opti...
def _incrdecr(self, key, is_negative, delta, namespace=None, initial_value=None):
rpc = self._incrdecr_async(key, is_negative, delta, namespace, initial_value) return rpc.get_result()
'Async version of _incrdecr(). Returns: A UserRPC instance whose get_result() method returns the same kind of value as _incrdecr() returns.'
def _incrdecr_async(self, key, is_negative, delta, namespace=None, initial_value=None, rpc=None):
if (not isinstance(delta, (int, long))): raise TypeError(('Delta must be an integer or long, received %r' % delta)) if (delta < 0): raise ValueError('Delta must not be negative.') if (not isinstance(key, basestring)): try: it = iter(key...
'Offsets multiple keys by a delta, incrementing and decrementing in batch. Args: mapping: Dictionary mapping keys to deltas (positive or negative integers) to apply to each corresponding key. key_prefix: Prefix for to prepend to all keys. initial_value: Initial value to put in the cache, if it doesn\'t already exist. T...
def offset_multi(self, mapping, key_prefix='', namespace=None, initial_value=None):
rpc = self.offset_multi_async(mapping, key_prefix, namespace, initial_value) return rpc.get_result()
'Async version of offset_multi(). Returns: A UserRPC instance whose get_result() method returns a dict just like offset_multi() returns.'
def offset_multi_async(self, mapping, key_prefix='', namespace=None, initial_value=None, rpc=None):
initial_flags = None if (initial_value is not None): if (not isinstance(initial_value, (int, long))): raise TypeError('initial_value must be an integer') if (initial_value < 0): raise ValueError('initial_value must be >= 0') if isinstance(i...
'Constructor.'
def __init__(self, service_name='app_identity_service'):
super(AppIdentityServiceStub, self).__init__(service_name)
'Implementation of AppIdentityService::SignForApp.'
def _Dynamic_SignForApp(self, request, response):
if (not CRYPTO_LIB_INSTALLED): raise NotImplementedError('Unable to import the pycrypto module,\n SignForApp is disabled.') rsa_obj = RSA.construct((N, E, D...
'Implementation of AppIdentityService::GetPublicCertificatesForApp'
def _Dynamic_GetPublicCertificatesForApp(self, request, response):
cert = response.add_public_certificate_list() cert.set_key_name(SIGNING_KEY_NAME) cert.set_x509_certificate_pem(X509_PUBLIC_CERT)
'Implementation of AppIdentityService::GetServiceAccountName'
def _Dynamic_GetServiceAccountName(self, request, response):
response.set_service_account_name(APP_SERVICE_ACCOUNT_NAME)
'Implementation of AppIdentityService::GetAccessToken. This API returns an invalid token, as the dev_appserver does not have access to an actual service account.'
def _Dynamic_GetAccessToken(self, request, response):
token = ':'.join(request.scope_list()) service_account_id = request.service_account_id() if service_account_id: token += ('.%d' % service_account_id) response.set_access_token(('InvalidToken:%s:%s' % (token, (time.time() % 100)))) response.set_expiration_time((int(time.time()) + 1800))
'Make a SignForApp RPC call. Args: request: a SignForAppRequest instance. rpc: Optional RPC instance to use for the call. callback: Optional final callback. Will be called as callback(rpc, result) when the rpc completes. If None, the call is synchronous. response: Optional ProtocolMessage to be filled in with response....
def SignForApp(self, request, rpc=None, callback=None, response=None):
if (response is None): response = SignForAppResponse return self._MakeCall(rpc, self._full_name_SignForApp, 'SignForApp', request, response, callback, self._protorpc_SignForApp)
'Make a GetPublicCertificatesForApp RPC call. Args: request: a GetPublicCertificateForAppRequest instance. rpc: Optional RPC instance to use for the call. callback: Optional final callback. Will be called as callback(rpc, result) when the rpc completes. If None, the call is synchronous. response: Optional ProtocolMessa...
def GetPublicCertificatesForApp(self, request, rpc=None, callback=None, response=None):
if (response is None): response = GetPublicCertificateForAppResponse return self._MakeCall(rpc, self._full_name_GetPublicCertificatesForApp, 'GetPublicCertificatesForApp', request, response, callback, self._protorpc_GetPublicCertificatesForApp)
'Make a GetServiceAccountName RPC call. Args: request: a GetServiceAccountNameRequest instance. rpc: Optional RPC instance to use for the call. callback: Optional final callback. Will be called as callback(rpc, result) when the rpc completes. If None, the call is synchronous. response: Optional ProtocolMessage to be fi...
def GetServiceAccountName(self, request, rpc=None, callback=None, response=None):
if (response is None): response = GetServiceAccountNameResponse return self._MakeCall(rpc, self._full_name_GetServiceAccountName, 'GetServiceAccountName', request, response, callback, self._protorpc_GetServiceAccountName)
'Make a GetAccessToken RPC call. Args: request: a GetAccessTokenRequest instance. rpc: Optional RPC instance to use for the call. callback: Optional final callback. Will be called as callback(rpc, result) when the rpc completes. If None, the call is synchronous. response: Optional ProtocolMessage to be filled in with r...
def GetAccessToken(self, request, rpc=None, callback=None, response=None):
if (response is None): response = GetAccessTokenResponse return self._MakeCall(rpc, self._full_name_GetAccessToken, 'GetAccessToken', request, response, callback, self._protorpc_GetAccessToken)
'Creates a Stubby RPC server. See BaseRpcServer.__init__ in rpcserver.py for detail on arguments.'
def __init__(self, *args, **kwargs):
if (_server_stub_base_class is object): raise NotImplementedError('Add //net/rpc/python:rpcserver as a dependency for Stubby server support.') _server_stub_base_class.__init__(self, 'apphosting.SigningService', *args, **kwargs)
'Creates a new SigningService Stubby client stub. Args: rpc_stub_parameters: an RPC_StubParameter instance. service_name: the service name used by the Stubby server.'
@staticmethod def NewStub(rpc_stub_parameters, service_name=None):
if (_client_stub_base_class is object): raise RuntimeError('Add //net/rpc/python as a dependency to use Stubby') return _SigningService_ClientStub(rpc_stub_parameters, service_name)
'Creates a new SigningService Stubby2 client stub. Args: server: host:port or bns address. channel: directly use a channel to create a stub. Will ignore server argument if this is specified. service_name: the service name used by the Stubby server.'
@staticmethod def NewRPC2Stub(server=None, channel=None, service_name=None):
if (_client_stub_base_class is object): raise RuntimeError('Add //net/rpc/python as a dependency to use Stubby') return _SigningService_RPC2ClientStub(server, channel, service_name)
'Handles a SignForApp RPC call. You should override this. Args: rpc: a Stubby RPC object request: a SignForAppRequest that contains the client request response: a SignForAppResponse that should be modified to send the response'
def SignForApp(self, rpc, request, response):
raise NotImplementedError
'Handles a GetPublicCertificatesForApp RPC call. You should override this. Args: rpc: a Stubby RPC object request: a GetPublicCertificateForAppRequest that contains the client request response: a GetPublicCertificateForAppResponse that should be modified to send the response'
def GetPublicCertificatesForApp(self, rpc, request, response):
raise NotImplementedError
'Handles a GetServiceAccountName RPC call. You should override this. Args: rpc: a Stubby RPC object request: a GetServiceAccountNameRequest that contains the client request response: a GetServiceAccountNameResponse that should be modified to send the response'
def GetServiceAccountName(self, rpc, request, response):
raise NotImplementedError
'Handles a GetAccessToken RPC call. You should override this. Args: rpc: a Stubby RPC object request: a GetAccessTokenRequest that contains the client request response: a GetAccessTokenResponse that should be modified to send the response'
def GetAccessToken(self, rpc, request, response):
raise NotImplementedError
'Sets attributes on Python RPC handlers. See BaseRpcServer in rpcserver.py for details.'
def _AddMethodAttributes(self):
rpcserver._GetHandlerDecorator(self.SignForApp.im_func, SignForAppRequest, SignForAppResponse, None, 'none') rpcserver._GetHandlerDecorator(self.GetPublicCertificatesForApp.im_func, GetPublicCertificateForAppRequest, GetPublicCertificateForAppResponse, None, 'none') rpcserver._GetHandlerDecorator(self.GetSe...
'Ctor. title is the name of this particular entity, e.g. Bob Jones or Mom\'s Birthday Party. kind_properties is a list of property names that should be included in this entity\'s XML encoding as first-class XML elements, instead of <property> elements. \'title\' and \'content\' are added to kind_properties automaticall...
def __init__(self, kind, title, kind_properties, contact_properties=[]):
datastore.Entity.__init__(self, kind) if (not isinstance(title, types.StringTypes)): raise datastore_errors.BadValueError(('Expected a string for title; received %s (a %s).' % (title, datastore_types.typename(title)))) self['title'] = title self['content'] = '' self._...
'Convert the properties that are part of this gd kind to XML. For testability, the XML elements in the output are sorted alphabetically by property name. Returns: string # the XML representation of the gd kind properties'
def _KindPropertiesToXml(self):
properties = self._kind_properties.intersection(set(self.keys())) xml = u'' for prop in sorted(properties): prop_xml = saxutils.quoteattr(prop)[1:(-1)] value = self[prop] has_toxml = (hasattr(value, 'ToXml') or (isinstance(value, list) and hasattr(value[0], 'ToXml'))) for val...
'Convert this kind\'s Contact properties kind to XML. For testability, the XML elements in the output are sorted alphabetically by property name. Returns: string # the XML representation of the Contact properties'
def _ContactPropertiesToXml(self):
properties = self._contact_properties.intersection(set(self.keys())) xml = u'' for prop in sorted(properties): values = self[prop] if (not isinstance(values, list)): values = [values] for value in values: assert isinstance(value, datastore_types.Key) ...
'Convert all of this entity\'s properties that *aren\'t* part of this gd kind to XML. Returns: string # the XML representation of the leftover properties'
def _LeftoverPropertiesToXml(self):
leftovers = set(self.keys()) leftovers -= self._kind_properties leftovers -= self._contact_properties if leftovers: return (u'\n ' + '\n '.join(self._PropertiesToXml(leftovers))) else: return u''
'Returns an XML representation of this entity, as a string.'
def ToXml(self):
xml = (GdKind.HEADER % self.kind().lower()) xml += self._KindPropertiesToXml() xml += self._ContactPropertiesToXml() xml += self._LeftoverPropertiesToXml() xml += GdKind.FOOTER return xml
'Override GdKind.ToXml() to special-case author, gd:where, gd:when, and gd:eventStatus.'
def ToXml(self):
xml = (GdKind.HEADER % self.kind().lower()) self._kind_properties = set(Contact.KIND_PROPERTIES) xml += self._KindPropertiesToXml() if ('author' in self): xml += ('\n <author><name>%s</name></author>' % self['author']) if ('eventStatus' in self): xml += ('\n <gd:eventSt...
'Override GdKind.ToXml() to put some properties inside a gd:contactSection.'
def ToXml(self):
xml = (GdKind.HEADER % self.kind().lower()) self._kind_properties = set(Contact.KIND_PROPERTIES) xml += self._KindPropertiesToXml() xml += Contact.CONTACT_SECTION_HEADER self._kind_properties = set(Contact.CONTACT_SECTION_PROPERTIES) xml += self._KindPropertiesToXml() xml += Contact.CONTACT_...
'Write data to the file. Args: data: byte array, string or iterable over bytes.'
def write(self, data):
raise NotImplementedError()
'Read data from file. Reads data from current position and advances position past the read data block. Args: size: number of bytes to read. Returns: iterable over bytes. If number of bytes read is less then \'size\' argument, it is assumed that end of file was reached.'
def read(self, size):
raise NotImplementedError()
'Get current file position. Returns: current position as a byte offset in the file as integer.'
def tell(self):
raise NotImplementedError()
'Constructor. Args: writer: a writer to use. Should conform to FileWriter interface.'
def __init__(self, writer, _pad_last_block=True):
self.__writer = writer self.__position = 0 self.__entered = False self.__pad_last_block = _pad_last_block
'Write single physical record.'
def __write_record(self, record_type, data):
length = len(data) crc = crc32c.crc_update(crc32c.CRC_INIT, [record_type]) crc = crc32c.crc_update(crc, data) crc = crc32c.crc_finalize(crc) self.__writer.write(struct.pack(HEADER_FORMAT, _mask_crc(crc), length, record_type)) self.__writer.write(data) self.__position += (HEADER_LENGTH + leng...
'Write single record. Args: data: record data to write as string, byte array or byte sequence.'
def write(self, data):
if (not self.__entered): raise Exception("RecordWriter should be used only with 'with' statement.") block_remaining = (BLOCK_SIZE - (self.__position % BLOCK_SIZE)) if (block_remaining < HEADER_LENGTH): self.__writer.write(('\x00' * block_remaining)) self.__positi...
'Try reading a record. Returns: (data, record_type) tuple. Raises: EOFError: when end of file was reached. InvalidRecordError: when valid record could not be read.'
def __try_read_record(self):
block_remaining = (BLOCK_SIZE - (self.__reader.tell() % BLOCK_SIZE)) if (block_remaining < HEADER_LENGTH): return ('', RECORD_TYPE_NONE) header = self.__reader.read(HEADER_LENGTH) if (len(header) != HEADER_LENGTH): raise EOFError(('Read %s bytes instead of %s' % (len(heade...
'Skip reader to the block boundary.'
def __sync(self):
pad_length = (BLOCK_SIZE - (self.__reader.tell() % BLOCK_SIZE)) if (pad_length and (pad_length != BLOCK_SIZE)): data = self.__reader.read(pad_length) if (len(data) != pad_length): raise EOFError(('Read %d bytes instead of %d' % (len(data), pad_length)))
'Reads record from current position in reader.'
def read(self):
data = None while True: last_offset = self.tell() try: (chunk, record_type) = self.__try_read_record() if (record_type == RECORD_TYPE_NONE): self.__sync() elif (record_type == RECORD_TYPE_FULL): if (data is not None): ...
'Return file\'s current position.'
def tell(self):
return self.__reader.tell()
'Set the file\'s current position. Arguments are passed directly to the underlying reader.'
def seek(self, *args, **kwargs):
return self.__reader.seek(*args, **kwargs)
'Constructor. Args: blob_storage: apphosting.api.blobstore.blobstore_stub.BlobStorage instance.'
def __init__(self, blob_storage):
self.blob_storage = blob_storage self.uploads = {} self.finalized = set() self.sequence_keys = {}
'Checks if there is an upload at this filename.'
def has_upload(self, filename):
return (filename in self.uploads)
'Marks file as finalized.'
def finalize(self, filename):
upload = self.uploads[filename] self.finalized.add(filename) upload.buf.seek(0) self.blob_storage.StoreBlob(self.get_blob_key(upload.key), upload.buf) del self.sequence_keys[filename] encoded_key = blobstore.create_gs_key(upload.key) file_info = datastore.Entity(GS_INFO_KIND, name=encoded_ke...
'Converts a Google Storage key into a base64 encoded blob key/filename.'
@staticmethod def get_blob_key(key):
return base64.urlsafe_b64encode(key)
'Checks if file is already finalized.'
def is_finalized(self, filename):
assert (filename in self.uploads) return (filename in self.finalized)
'Starts a new upload based on the specified CreateRequest.'
def start_upload(self, request):
mime_type = None gs_filename = request.filename() ignored_parameters = [gs._CACHE_CONTROL_PARAMETER, gs._CANNED_ACL_PARAMETER, gs._CONTENT_DISPOSITION_PARAMETER, gs._CONTENT_ENCODING_PARAMETER] for param in request.parameters_list(): name = param.name() if (name == gs._MIME_TYPE_PARAMETE...
'Appends data to the upload filename.'
def append(self, filename, data, sequence_key):
assert (not self.is_finalized(filename)) if sequence_key: current_sequence_key = self.sequence_keys[filename] if (current_sequence_key and (current_sequence_key >= sequence_key)): raise_error(file_service_pb.FileServiceErrors.SEQUENCE_KEY_OUT_OF_ORDER, error_detail=current_sequence_k...
'Returns: file info for a finalized file with given filename'
def stat(self, filename):
blob_key = blobstore.create_gs_key(filename) try: return datastore.Get(datastore.Key.from_path(GS_INFO_KIND, blob_key, namespace='')) except datastore_errors.EntityNotFoundError: raise raise_error(file_service_pb.FileServiceErrors.EXISTENCE_ERROR, filename)
'listdir. Args: request: ListDir RPC request. response: ListDir RPC response. Returns: A list of fully qualified filenames under a certain path sorted by in char order.'
def listdir(self, request, response):
path = request.path() prefix = (request.prefix() if request.has_prefix() else '') q = datastore.Query(GS_INFO_KIND, namespace='') fully_qualified_name = '/'.join([path, prefix]) if request.has_marker(): q['filename >'] = '/'.join([path, request.marker()]) else: q['filename ...
'Checks if the file is opened for appending or reading.'
@property def is_appending(self):
return (self.open_mode == file_service_pb.OpenRequest.APPEND)
'Fill response with file stat. Current implementation only fills length, finalized, filename, and content type. File must be opened in read mode before stat is called.'
def stat(self, request, response):
file_info = self.file_storage.stat(self.filename) file_stat = response.add_stat() file_stat.set_filename(file_info['filename']) file_stat.set_finalized(True) file_stat.set_length(file_info['size']) file_stat.set_ctime(_to_seconds(file_info['creation'])) file_stat.set_mtime(_to_seconds(file_i...
'Copies up to max_bytes starting at pos into response from filename.'
def read(self, request, response):
if self.is_appending: raise_error(file_service_pb.FileServiceErrors.WRONG_OPEN_MODE) self.buf.seek(request.pos()) data = self.buf.read(request.max_bytes()) response.set_data(data)
'Appends data to filename.'
def append(self, request, response):
if (not self.is_appending): raise_error(file_service_pb.FileServiceErrors.WRONG_OPEN_MODE) self.file_storage.append(self.filename, request.data(), request.sequence_key())
'Finalize a file. Copies temp file data to permanent location for reading.'
def finalize(self):
if (not self.is_appending): raise_error(file_service_pb.FileServiceErrors.WRONG_OPEN_MODE) elif self.file_storage.is_finalized(self.filename): raise_error(file_service_pb.FileServiceErrors.FINALIZATION_ERROR, 'File is already finalized') self.file_storage.finalize(self.filename)
'Constructor. Args: blob_storage: An instance of apphosting.api.blobstore.blobstore_stub.BlobStorage to use for blob integration.'
def __init__(self, blob_storage):
self.blob_keys = {} self.blobstore_files = set() self.finalized_files = set() self.created_files = set() self.data_files = {} self.sequence_keys = {} self.blob_storage = blob_storage self.blob_content_types = {} self.blob_file_names = {}
'Marks file as finalized.'
def finalize(self, filename):
if self.is_finalized(filename): raise_error(file_service_pb.FileServiceErrors.FINALIZATION_ERROR, 'File is already finalized') self.finalized_files.add(filename)
'Checks if file is already finalized.'
def is_finalized(self, filename):
return (filename in self.finalized_files)
'Gets blob key for blob creation ticket.'
def get_blob_key(self, ticket):
return self.blob_keys.get(ticket)
'Register blob key for a ticket.'
def register_blob_key(self, ticket, blob_key):
self.blob_keys[ticket] = blob_key
'Checks if blobstore file was already created.'
def has_blobstore_file(self, filename):
return (filename in self.blobstore_files)
'Registers a created blob store file.'
def add_blobstore_file(self, request):
mime_type = None blob_filename = '' for param in request.parameters_list(): name = param.name() if (name == files_blobstore._MIME_TYPE_PARAMETER): mime_type = param.value() elif (name == files_blobstore._BLOBINFO_UPLOADED_FILENAME_PARAMETER): blob_filename = p...
'Get sequence key for a file.'
def get_sequence_key(self, filename):
return self.sequence_keys.get(filename, '')
'Set sequence key for a file.'
def set_sequence_key(self, filename, sequence_key):
self.sequence_keys[filename] = sequence_key
'Returns: file info for a finalized file with given filename.'
def stat(self, filename):
blob_key = files_blobstore.get_blob_key(filename) file_info = datastore.Get(datastore.Key.from_path(api_blobstore.BLOB_INFO_KIND, str(blob_key), namespace='')) if (file_info == None): raise raise_error(file_service_pb.FileServiceErrors.EXISTENCE_ERROR_MEATADATA_NOT_FOUND, filename) return file_i...
'Save filename temp data to a blobstore under given key.'
def save_blob(self, filename, blob_key):
f = self._get_data_file(filename) f.seek(0) self.blob_storage.StoreBlob(blob_key, f) f.seek(0, os.SEEK_END) size = f.tell() f.close() del self.data_files[filename] return size
'Get a temp data file for a file.'
def _get_data_file(self, filename):
if (not (filename in self.data_files)): f = tempfile.TemporaryFile() self.data_files[filename] = f return f return self.data_files[filename]
'Get md5 hexdigest of the blobfile with blobkey.'
def get_md5_from_blob(self, blobkey):
try: f = self.blob_storage.OpenBlob(blobkey) file_md5 = hashlib.md5() file_md5.update(f.read()) return file_md5.hexdigest() finally: f.close()
'Append data to file.'
def append(self, filename, data):
self._get_data_file(filename).write(data)
'Constructor. Args: open_request: An instance of open file request. file_storage: An instance of BlobstoreStorage.'
def __init__(self, open_request, file_storage):
self.filename = open_request.filename() self.file_storage = file_storage self.blob_reader = None self.content_type = None self.mime_content_type = None open_mode = open_request.open_mode() content_type = open_request.content_type() if (not self.filename.startswith(_BLOBSTORE_DIRECTORY)):...
'Checks if the file is opened for appending or reading.'
@property def is_appending(self):
return (self.blob_reader == None)
'Fill response with file stat. Current implementation only fills length, finalized, filename, and content type. File must be opened in read mode before stat is called.'
def stat(self, request, response):
file_info = self.file_storage.stat(self.filename) file_stat = response.add_stat() file_stat.set_filename(self.filename) file_stat.set_finalized(True) file_stat.set_length(file_info['size']) file_stat.set_ctime(_to_seconds(file_info['creation'])) file_stat.set_mtime(_to_seconds(file_info['cre...
'Read data from file Args: request: An instance of file_service_pb.ReadRequest. response: An instance of file_service_pb.ReadResponse.'
def read(self, request, response):
if self.is_appending: raise_error(file_service_pb.FileServiceErrors.WRONG_OPEN_MODE) self.blob_reader.seek(request.pos()) response.set_data(self.blob_reader.read(request.max_bytes()))
'Append data to file. Args: request: An instance of file_service_pb.AppendRequest. response: An instance of file_service_pb.AppendResponse.'
def append(self, request, response):
sequence_key = request.sequence_key() if sequence_key: current_sequence_key = self.file_storage.get_sequence_key(self.filename) if (current_sequence_key and (current_sequence_key >= sequence_key)): raise_error(file_service_pb.FileServiceErrors.SEQUENCE_KEY_OUT_OF_ORDER, error_detail=...
'Finalize a file. Copies temp file data to the blobstore.'
def finalize(self):
self.file_storage.finalize(self.filename) blob_key = _random_string(64) self.file_storage.register_blob_key(self.ticket, blob_key) size = self.file_storage.save_blob(self.filename, blob_key) blob_info = datastore.Entity(api_blobstore.BLOB_INFO_KIND, name=str(blob_key), namespace='') blob_info['c...
'Constructor.'
def __init__(self, blob_storage):
super(FileServiceStub, self).__init__('file', max_request_size=MAX_REQUEST_SIZE) self.open_files = {} self.file_storage = BlobstoreStorage(blob_storage) self.gs_storage = GoogleStorage(blob_storage)
'Handler for Open RPC call.'
def _Dynamic_Open(self, request, response):
filename = request.filename() if (request.exclusive_lock() and (filename in self.open_files)): raise_error(file_service_pb.FileServiceErrors.EXCLUSIVE_LOCK_FAILED) if filename.startswith(_BLOBSTORE_DIRECTORY): self.open_files[filename] = BlobstoreFile(request, self.file_storage) elif fil...
'Handler for Close RPC call.'
def _Dynamic_Close(self, request, response):
filename = request.filename() finalize = request.finalize() if (not (filename in self.open_files)): raise_error(file_service_pb.FileServiceErrors.FILE_NOT_OPENED) if finalize: self.open_files[filename].finalize() del self.open_files[filename]
'Handler for Stat RPC call.'
def _Dynamic_Stat(self, request, response):
filename = request.filename() if (not (filename in self.open_files)): raise_error(file_service_pb.FileServiceErrors.FILE_NOT_OPENED) file = self.open_files[filename] if file.is_appending: raise_error(file_service_pb.FileServiceErrors.WRONG_OPEN_MODE) file.stat(request, response)
'Handler for Read RPC call.'
def _Dynamic_Read(self, request, response):
filename = request.filename() if (not (filename in self.open_files)): raise_error(file_service_pb.FileServiceErrors.FILE_NOT_OPENED) self.open_files[filename].read(request, response)
'Handler for Append RPC call.'
def _Dynamic_Append(self, request, response):
filename = request.filename() if (not (filename in self.open_files)): raise_error(file_service_pb.FileServiceErrors.FILE_NOT_OPENED) self.open_files[filename].append(request, response)
'Handler for GetCapabilities RPC call.'
def _Dynamic_GetCapabilities(self, request, response):
response.add_filesystem('blobstore') response.add_filesystem('gs') response.set_shuffle_available(False)
'Handler for GetDefaultGsBucketName RPC call.'
def _Dynamic_GetDefaultGsBucketName(self, request, response):
response.set_default_gs_bucket_name('app_default_bucket')
'Handler for ListDir RPC call. Only for dev app server. See b/6761691.'
def _Dynamic_ListDir(self, request, response):
path = request.path() if (not path.startswith(_GS_PREFIX)): raise_error(file_service_pb.FileServiceErrors.UNSUPPORTED_FILE_SYSTEM) self.gs_storage.listdir(request, response)
'Constructor. Args: filename: File\'s name as string. content_type: File\'s content type. Value from FileContentType.ContentType enum.'
def __init__(self, filename, mode, content_type, exclusive_lock):
self._filename = filename self._closed = False self._content_type = content_type self._mode = mode self._exclusive_lock = exclusive_lock self._offset = 0 self._open()
'Close file. Args: finalize: Specifies if file should be finalized upon closing.'
def close(self, finalize=False):
if self._closed: return self._closed = True request = file_service_pb.CloseRequest() response = file_service_pb.CloseResponse() request.set_filename(self._filename) request.set_finalize(finalize) self._make_rpc_call_with_retry('Close', request, response)
'Write data to file. Args: data: Data to be written to the file. For RAW files it should be a string or byte sequence. sequence_key: Sequence key to use for write. Is used for RAW files only. File API infrastructure ensures that sequence_key are monotonically increasing. If sequence key less than previous one is used, ...
def write(self, data, sequence_key=None):
if (self._content_type == RAW): request = file_service_pb.AppendRequest() response = file_service_pb.AppendResponse() request.set_filename(self._filename) request.set_data(data) if sequence_key: request.set_sequence_key(sequence_key) self._make_rpc_call_wi...
'Return file\'s current position. Is valid only when file is opened for read.'
def tell(self):
self._verify_read_mode() return self._offset
'Set the file\'s current position. Args: offset: seek offset as number. whence: seek mode. Supported modes are os.SEEK_SET (absolute seek), and os.SEEK_CUR (seek relative to the current position) and os.SEEK_END (seek relative to the end, offset should be negative).'
def seek(self, offset, whence=os.SEEK_SET):
self._verify_read_mode() if (whence == os.SEEK_SET): self._offset = offset elif (whence == os.SEEK_CUR): self._offset += offset elif (whence == os.SEEK_END): file_stat = self.stat() self._offset = (file_stat.st_size + offset) else: raise InvalidArgumentError('...
'Read data from RAW file. Args: size: Number of bytes to read as integer. Actual number of bytes read might be less than specified, but it\'s never 0 unless current offset is at the end of the file. If it is None, then file is read until the end. Returns: A string with data read.'
def read(self, size=None):
self._verify_read_mode() if (self._content_type != RAW): raise UnsupportedContentTypeError(('Unsupported content type: %s' % self._content_type)) buf = StringIO.StringIO() original_offset = self._offset try: if (size is None): size = sys.maxint while (siz...
'Get status of a finalized file. Returns: a _FileStat object similar to that returned by python\'s os.stat(path). Throws: FinalizationError if file is not finalized.'
def stat(self):
self._verify_read_mode() request = file_service_pb.StatRequest() response = file_service_pb.StatResponse() request.set_filename(self._filename) _make_call('Stat', request, response) if (response.stat_size() == 0): raise ExistenceError(('File %s not found.' % self._filename)) ...