desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Enable the mail stub. The email service stub is only available in dev_appserver because it uses the subprocess module. Args: enable: True, if the fake service should be enabled, False if real service should be disabled. stub_kw_args: Keyword arguments passed on to the service stub.'
def init_mail_stub(self, enable=True, **stub_kw_args):
if (not enable): self._disable_stub(MAIL_SERVICE_NAME) return stub = mail_stub.MailServiceStub(**stub_kw_args) self._register_stub(MAIL_SERVICE_NAME, stub)
'Enable the memcache stub. Args: enable: True, if the fake service should be enabled, False if real service should be disabled.'
def init_memcache_stub(self, enable=True):
if (not enable): self._disable_stub(MEMCACHE_SERVICE_NAME) return stub = memcache_stub.MemcacheServiceStub() self._register_stub(MEMCACHE_SERVICE_NAME, stub)
'Enable the taskqueue stub. Args: enable: True, if the fake service should be enabled, False if real service should be disabled. stub_kw_args: Keyword arguments passed on to the service stub.'
def init_taskqueue_stub(self, enable=True, **stub_kw_args):
if (not enable): self._disable_stub(TASKQUEUE_SERVICE_NAME) return stub = taskqueue_stub.TaskQueueServiceStub(**stub_kw_args) self._register_stub(TASKQUEUE_SERVICE_NAME, stub)
'Enable the urlfetch stub. The urlfetch service stub uses the urllib module to make requests. Because on appserver urllib also relies the urlfetch infrastructure, using this stub will have no effect. Args: enable: True, if the fake service should be enabled, False if real service should be disabled.'
def init_urlfetch_stub(self, enable=True):
if (not enable): self._disable_stub(URLFETCH_SERVICE_NAME) return urlmatchers_to_fetch_functions = [] urlmatchers_to_fetch_functions.extend(gcs_dispatcher.URLMATCHERS_TO_FETCH_FUNCTIONS) stub = urlfetch_stub.URLFetchServiceStub(urlmatchers_to_fetch_functions=urlmatchers_to_fetch_function...
'Enable the users stub. Args: enable: True, if the fake service should be enabled, False if real service should be disabled. stub_kw_args: Keyword arguments passed on to the service stub.'
def init_user_stub(self, enable=True, **stub_kw_args):
if (not enable): self._disable_stub(USER_SERVICE_NAME) return stub = user_service_stub.UserServiceStub(**stub_kw_args) self._register_stub(USER_SERVICE_NAME, stub)
'Enable the xmpp stub. Args: enable: True, if the fake service should be enabled, False if real service should be disabled.'
def init_xmpp_stub(self, enable=True):
if (not enable): self._disable_stub(XMPP_SERVICE_NAME) return stub = xmpp_service_stub.XmppServiceStub() self._register_stub(XMPP_SERVICE_NAME, stub)
'Enable a stub by service name. Args: service_name: Name of service to initialize. This name should be the name used by the service stub. Additional arguments are passed along to the specific stub initializer. Raises: NotActivatedError: When this function is called before testbed is activated or after it is deactivate...
def _init_stub(self, service_name, *args, **kwargs):
if (not self._activated): raise NotActivatedError('The testbed is not activated.') method_name = INIT_STUB_METHOD_NAMES.get(service_name, None) if (method_name is None): msg = ('The "%s" service is not supported by testbed' % service_name) raise StubN...
'Enable all known testbed stubs. Args: enable: True, if the fake services should be enabled, False if real services should be disabled.'
def init_all_stubs(self, enable=True):
for service_name in SUPPORTED_SERVICES: self._init_stub(service_name, enable)
'Mapreduce done callback to delete job data if it was successful.'
def post(self):
if ('Mapreduce-Id' in self.request.headers): mapreduce_id = self.request.headers['Mapreduce-Id'] mapreduce_state = model.MapreduceState.get_by_job_id(mapreduce_id) mapreduce_params = mapreduce_state.mapreduce_spec.params db_config = _CreateDatastoreConfig() if (mapreduce_stat...
'Record the key to allocate max id. Args: key: Datastore key.'
def allocate_max_id(self, key):
path = key.to_path() if (len(path) == 2): path_tuple = ('Foo', 1) key_id = path[(-1)] else: path_tuple = (path[0], path[1], 'Foo', 1) key_id = None for path_element in path[2:]: if isinstance(path_element, (int, long)): key_id = max(key_id,...
'Rendering method that can be called by main.py or get. This method executes no action, so the method by which it is accessed is immaterial. Creating a form with get may be a desirable function. That is, if this builtin is turned on, anyone can create a form to delete a kind by simply linking to the ConfirmDeleteHand...
@classmethod def Render(cls, handler):
namespace = handler.request.get('namespace') kinds = handler.request.get_all('kind') (sizes_known, size_total, remainder) = utils.ParseKindsAndSizes(kinds) (namespace_str, kind_str) = utils.GetPrintableStrs(namespace, kinds) template_params = {'form_target': DoDeleteHandler.SUFFIX, 'kind_list': kind...
'Handler for get requests to datastore_admin/confirm_delete.'
def get(self):
ConfirmDeleteHandler.Render(self)
'Handler for get requests to datastore_admin/delete.do. Status of executed jobs is displayed.'
def get(self):
jobs = self.request.get_all('job') error = self.request.get('error', '') xsrf_error = self.request.get('xsrf_error', '') template_params = {'job_list': jobs, 'mapreduce_detail': self.MAPREDUCE_DETAIL, 'error': error, 'xsrf_error': xsrf_error, 'datastore_admin_home': utils.config.BASE_PATH} utils.Ren...
'Handler for post requests to datastore_admin/delete.do. Jobs are executed and user is redirected to the get handler.'
def post(self):
namespace = self.request.get('namespace') kinds = self.request.get_all('kind') (namespace_str, kinds_str) = utils.GetPrintableStrs(namespace, kinds) token = self.request.get('xsrf_token') jobs = [] if utils.ValidateXsrfToken(token, XSRF_ACTION): try: op = utils.StartOperation...
'Make exception handling overrideable by tests. In normal cases, return only the error string; do not fail to render the page for user.'
def _HandleException(self, e):
return str(e)
'Handler for get requests to datastore_admin/confirm_delete.'
def ListActions(self, error=None):
use_stats_kinds = False kinds = [] try: kinds = self.GetKinds() if (not kinds): use_stats_kinds = True except datastore_errors.Error: use_stats_kinds = True (last_stats_update, kind_stats) = _GetDatastoreStats(kinds, use_stats_kinds=use_stats_kinds) template_p...
'Obtain a list of all kind names from the datastore. Args: all_ns: If true, list kind names for all namespaces. If false, list kind names only for the current namespace. Returns: An alphabetized list of kinds for the specified namespace(s).'
def GetKinds(self, all_ns=True):
if all_ns: result = self.GetKindsForAllNamespaces() else: result = self.GetKindsForCurrentNamespace() return result
'Obtain a list of all kind names from the datastore, *regardless* of namespace. The result is alphabetized and deduped.'
def GetKindsForAllNamespaces(self):
namespace_list = [ns.namespace_name for ns in metadata.Namespace.all().run(limit=99999999)] kind_itr_list = [metadata.Kind.all(namespace=ns).run(limit=99999999, batch_size=99999999) for ns in namespace_list] kind_name_set = set() for kind_itr in kind_itr_list: for kind in kind_itr: k...
'Obtain a list of all kind names from the datastore for the current namespace. The result is alphabetized.'
def GetKindsForCurrentNamespace(self):
kinds = metadata.Kind.all().order('__key__').fetch(99999999) kind_names = [] for kind in kinds: kind_name = kind.kind_name if utils.IsKindNameVisible(kind_name): kind_names.append(kind_name) return kind_names
'Obtain a list of operation, ordered by last_updated.'
def GetOperations(self, active=False, limit=100):
query = utils.DatastoreAdminOperation.all() if active: query.filter('status = ', utils.DatastoreAdminOperation.STATUS_ACTIVE) else: query.filter('status IN ', [utils.DatastoreAdminOperation.STATUS_COMPLETED, utils.DatastoreAdminOperation.STATUS_FAILED, utils.DatastoreAdminOperati...
'Obtain a list of backups.'
def GetBackups(self, limit=100):
query = backup_handler.BackupInformation.all() query.filter('complete_time > ', 0) backups = query.fetch((max(10000, limit) if limit else 1000)) backups = sorted(backups, key=operator.attrgetter('complete_time'), reverse=True) return backups[:limit]
'Obtain a list of pending backups.'
def GetPendingBackups(self, limit=100):
query = backup_handler.BackupInformation.all() query.filter('complete_time = ', None) backups = query.fetch((max(10000, limit) if limit else 1000)) backups = sorted(backups, key=operator.attrgetter('start_time'), reverse=True) return backups[:limit]
'Rendering method that can be called by main.py. Args: handler: the webapp2.RequestHandler invoking the method'
@classmethod def Render(cls, handler):
kinds = handler.request.get_all('kind') (sizes_known, size_total, remainder) = utils.ParseKindsAndSizes(kinds) notreadonly_warning = capabilities.CapabilitySet('datastore_v3', capabilities=['write']).is_enabled() blob_warning = bool(blobstore.BlobInfo.all().count(1)) template_params = {'form_target'...
'Rendering method that can be called by main.py. Args: handler: the webapp2.RequestHandler invoking the method'
@classmethod def Render(cls, handler):
requested_backup_ids = handler.request.get_all('backup_id') backups = [] gs_warning = False if requested_backup_ids: for backup in db.get(requested_backup_ids): if backup: backups.append(backup) gs_warning |= (backup.filesystem == files.GS_FILESYSTEM) ...
'Rendering method that can be called by main.py. Args: handler: the webapp2.RequestHandler invoking the method'
@classmethod def Render(cls, handler):
requested_backup_ids = handler.request.get_all('backup_id') backups = [] if requested_backup_ids: for backup in db.get(requested_backup_ids): if backup: backups.append(backup) template_params = {'form_target': DoBackupAbortHandler.SUFFIX, 'cancel_url': handler.request...
'Rendering method that can be called by main.py. Args: handler: the webapp2.RequestHandler invoking the method default_backup_id: default value for handler.request default_delete_backup_after_restore: default value for handler.request'
@classmethod def Render(cls, handler, default_backup_id=None, default_delete_backup_after_restore=False):
backup_id = handler.request.get('backup_id', default_backup_id) backup = (db.get(backup_id) if backup_id else None) notreadonly_warning = capabilities.CapabilitySet('datastore_v3', capabilities=['write']).is_enabled() original_app_warning = backup.original_app if (os.getenv('APPLICATION_ID') == orig...
'Rendering method that can be called by main.py. Args: handler: the webapp2.RequestHandler invoking the method'
@classmethod def Render(cls, handler):
gs_handle = handler.request.get('gs_handle') error = (None if gs_handle else 'Google Cloud Storage path is missing') other_backup_info_files = [] selected_backup_info_file = None backup_info_specified = False if (not error): try: gs_handle = gs_handle.rstrip() ...
'Rendering method that can be called by main.py. Args: handler: the webapp2.RequestHandler invoking the method'
@classmethod def Render(cls, handler):
backup_ids = handler.request.get_all('backup_id') template_params = {'backups': db.get(backup_ids), 'back_target': handler.request.get('cancel_url')} utils.RenderToResponse(handler, 'backup_information.html', template_params)
'Handler for get requests to datastore_admin backup operations. Status of executed jobs is displayed.'
def get(self):
jobs = self.request.get_all('job') tasks = self.request.get_all('task') error = self.request.get('error', '') xsrf_error = self.request.get('xsrf_error', '') template_params = {'job_list': jobs, 'task_list': tasks, 'mapreduce_detail': self.MAPREDUCE_DETAIL, 'error': error, 'xsrf_error': xsrf_error, ...
'Return the name of the HTML page for HTTP/GET requests.'
@property def _get_html_page(self):
raise NotImplementedError
'Return the name of the HTML page for HTTP/POST requests.'
@property def _get_post_html_page(self):
raise NotImplementedError
'Process the HTTP/POST request and return the result as parametrs.'
def _ProcessPostRequest(self):
raise NotImplementedError
'Handler for post requests to datastore_admin/backup.do. Redirects to the get handler after processing the request.'
def post(self):
token = self.request.get('xsrf_token') if (not utils.ValidateXsrfToken(token, XSRF_ACTION)): parameters = [('xsrf_error', '1')] else: try: parameters = self._ProcessPostRequest() except Exception as e: error = self._HandleException(e) parameters = ...
'Make exception handling overrideable by tests. Args: e: The exception to handle. Returns: The exception error string.'
def _HandleException(self, e):
return ('%s: %s' % (type(e), e))
'Handler for get requests to datastore_admin/backup.create.'
def get(self):
self.post()
'Handler for post requests to datastore_admin/backup.create.'
def post(self):
try: backup_prefix = self.request.get('name') if (not backup_prefix): if self.request.headers.get('X-AppEngine-Cron'): backup_prefix = 'cron-' else: backup_prefix = 'link-' backup_prefix_with_date = (backup_prefix + time.strftime('%Y_%m...
'Triggers backup mapper jobs and returns their ids.'
def _ProcessPostRequest(self):
try: backup = self.request.get('backup_name').strip() if (not backup): raise BackupValidationException('Unspecified backup name.') if BackupInformation.name_exists(backup): raise BackupValidationException(('Backup "%s" already exists.' % backup)) ...
'Handler for post requests to datastore_admin/backup_delete.do. Deletes are executed and user is redirected to the base-path handler.'
def post(self):
backup_ids = self.request.get_all('backup_id') token = self.request.get('xsrf_token') error = None if (backup_ids and utils.ValidateXsrfToken(token, XSRF_ACTION)): try: for backup_info in db.get(backup_ids): if backup_info: delete_backup_info(backu...
'Handler for post requests to datastore_admin/backup_abort.do. Abort is executed and user is redirected to the base-path handler.'
def post(self):
backup_ids = self.request.get_all('backup_id') token = self.request.get('xsrf_token') error = None if (backup_ids and utils.ValidateXsrfToken(token, XSRF_ACTION)): try: for backup_info in db.get(backup_ids): if backup_info: utils.AbortAdminOperatio...
'Triggers backup restore mapper jobs and returns their ids.'
def _ProcessPostRequest(self):
backup_id = self.request.get('backup_id') if (not backup_id): return [('error', 'Unspecified Backup.')] backup = db.get(db.Key(backup_id)) if (not backup): return [('error', 'Invalid Backup id.')] if backup.gs_handle: if (not is_readable_gs_handle(backup.gs_handle)):...
'Handler for post requests to datastore_admin/import_backup.do. Import is executed and user is redirected to the base-path handler.'
def post(self):
gs_handle = self.request.get('gs_handle') token = self.request.get('xsrf_token') error = None if (gs_handle and utils.ValidateXsrfToken(token, XSRF_ACTION)): try: (bucket_name, path) = parse_gs_handle(gs_handle) file_content = get_gs_object(bucket_name, path) ...
'Construct a BackupInfoWriter. Args: gs_bucket: Required string for the target GS bucket.'
def __init__(self, gs_bucket):
self.__gs_bucket = gs_bucket
'Write the metadata files for the given backup_info. Args: backup_info: Required BackupInformation. Returns: A list with Backup info filename followed by Kind info filenames.'
def write(self, backup_info):
fn = self._write_backup_info(backup_info) return ([fn] + self._write_kind_info(backup_info))
'Writes a backup_info_file. Args: backup_info: Required BackupInformation. Returns: Backup info filename.'
def _write_backup_info(self, backup_info):
filename = self._generate_filename(backup_info, '.backup_info') backup_info.gs_handle = filename info_file = files.open(files.gs.create(filename), 'a', exclusive_lock=True) try: with records.RecordsWriter(info_file) as writer: writer.write('1') writer.write(db.model_to_pr...
'Writes type information schema for each kind in backup_info. Args: backup_info: Required BackupInformation. Returns: A list with all created filenames.'
def _write_kind_info(self, backup_info):
filenames = [] for kind_backup_files in backup_info.get_kind_backup_files(): backup = self._create_kind_backup(backup_info, kind_backup_files) filename = self._generate_filename(backup_info, ('.%s.backup_info' % kind_backup_files.backup_kind)) self._write_kind_backup_info_file(filename, ...
'Creates and populate a backup_pb2.Backup.'
def _create_kind_backup(self, backup_info, kind_backup_files):
backup = backup_pb2.Backup() backup.backup_info.backup_name = backup_info.name backup.backup_info.start_timestamp = datastore_types.DatetimeToTimestamp(backup_info.start_time) backup.backup_info.end_timestamp = datastore_types.DatetimeToTimestamp(backup_info.complete_time) kind = kind_backup_files.b...
'Writes a kind backup_info. Args: filename: The name of the file to be created as string. backup: apphosting.ext.datastore_admin.Backup proto.'
@classmethod def _write_kind_backup_info_file(cls, filename, backup):
f = files.open(files.gs.create(filename), 'a', exclusive_lock=True) try: f.write(backup.SerializeToString()) finally: f.close(finalize=True)
'Construct a PropertyTypeInfo instance. Args: name: The name of the property as a string. is_repeated: A boolean that indicates if the property is repeated. primitive_types: Optional list of PrimitiveType integer values. embedded_entities: Optional list of EntityTypeInfo.'
def __init__(self, name, is_repeated=False, primitive_types=None, embedded_entities=None):
self.__name = name self.__is_repeated = is_repeated self.__primitive_types = (set(primitive_types) if primitive_types else set()) self.__embedded_entities = {} for entity in (embedded_entities or ()): if (entity.kind in self.__embedded_entities): self.__embedded_entities[entity.k...
'Merge a PropertyTypeInfo with this instance. Args: other: Required PropertyTypeInfo to merge. Returns: True if anything was changed. False otherwise. Raises: ValueError: if property names do not match. TypeError: if other is not instance of PropertyTypeInfo.'
def merge(self, other):
if (not isinstance(other, PropertyTypeInfo)): raise TypeError(('Expected PropertyTypeInfo, was %r' % (other,))) if (other.__name != self.__name): raise ValueError(('Property names mismatch (%s, %s)' % (self.__name, other.__name))) changed = False if (other.__is_repea...
'Add an populate a Field to the given entity_schema. Args: entity_schema: apphosting.ext.datastore_admin.EntitySchema proto.'
def populate_entity_schema_field(self, entity_schema):
if (not (self.__primitive_types or self.__embedded_entities)): return field = entity_schema.field.add() field.name = self.__name field_type = field.type.add() field_type.is_list = self.__is_repeated field_type.primitive_type.extend(self.__primitive_types) for embedded_entity in self....
'Construct an EntityTypeInfo instance. Args: kind: An optional kind name as string. properties: An optional list of PropertyTypeInfo.'
def __init__(self, kind=None, properties=None):
self.__kind = kind self.__properties = {} for property_type_info in (properties or ()): if (property_type_info.name in self.__properties): self.__properties[property_type_info.name].merge(property_type_info) else: self.__properties[property_type_info.name] = property_...
'Merge an EntityTypeInfo with this instance. Args: other: Required EntityTypeInfo to merge. Returns: True if anything was changed. False otherwise. Raises: ValueError: if kinds do not match. TypeError: if other is not instance of EntityTypeInfo.'
def merge(self, other):
if (not isinstance(other, EntityTypeInfo)): raise TypeError(('Expected EntityTypeInfo, was %r' % (other,))) if (other.__kind != self.__kind): raise ValueError(('Kinds mismatch (%s, %s)' % (self.__kind, other.__kind))) changed = False for (name, other_property) in other....
'Populates the given entity_schema with values from this instance. Args: entity_schema: apphosting.ext.datastore_admin.EntitySchema proto.'
def populate_entity_schema(self, entity_schema):
if self.__kind: entity_schema.kind = self.__kind for property_type_info in self.__properties.itervalues(): property_type_info.populate_entity_schema_field(entity_schema)
'Creates and populates an EntityTypeInfo from an EntityProto.'
@classmethod def create_from_entity_proto(cls, entity_proto):
properties = [cls.__get_property_type_info(property_proto) for property_proto in itertools.chain(entity_proto.property_list(), entity_proto.raw_property_list())] kind = utils.get_kind_from_entity_pb(entity_proto) return cls(kind, properties)
'Returns the type mapping for the provided property.'
@classmethod def __get_property_type_info(cls, property_proto):
name = property_proto.name() is_repeated = bool(property_proto.multiple()) primitive_type = None entity_type = None if property_proto.has_meaning(): primitive_type = MEANING_TO_PRIMITIVE_TYPE.get(property_proto.meaning()) if (primitive_type is None): value = property_proto.value(...
'Merge a SchemaAggregationResult or an EntityTypeInfo with this instance. Args: other: Required SchemaAggregationResult or EntityTypeInfo to merge. Returns: True if anything was changed. False otherwise.'
def merge(self, other):
if self.is_partial: return False if isinstance(other, SchemaAggregationResult): other = other.entity_type_info return self.entity_type_info.merge(other)
'Create SchemaAggregationResult instance. Args: backup_id: Required BackupInformation Key. kind_name: Required kind name as string. shard_id: Required shard id as string. Returns: A new SchemaAggregationResult instance.'
@classmethod def create(cls, backup_id, kind_name, shard_id):
parent = cls._get_parent_key(backup_id, kind_name) return SchemaAggregationResult(key_name=shard_id, parent=parent, entity_type_info=EntityTypeInfo(kind=kind_name))
'Retrieve SchemaAggregationResult from the Datastore. Args: backup_id: Required BackupInformation Key. kind_name: Required kind name as string. shard_id: Optional shard id as string. Returns: SchemaAggregationResult iterator or an entity if shard_id not None.'
@classmethod def load(cls, backup_id, kind_name, shard_id=None):
parent = cls._get_parent_key(backup_id, kind_name) if shard_id: key = datastore_types.Key.from_path(cls.kind(), shard_id, parent=parent) return SchemaAggregationResult.get(key) else: return db.Query(cls).ancestor(parent).run()
'Construct SchemaAggregationPool instance. Args: backup_id: Required BackupInformation Key. kind: Required kind name as string. shard_id: Required shard id as string.'
def __init__(self, backup_id, kind, shard_id):
self.__backup_id = backup_id self.__kind = kind self.__shard_id = shard_id self.__aggregation = SchemaAggregationResult.load(backup_id, kind, shard_id) if (not self.__aggregation): self.__aggregation = SchemaAggregationResult.create(backup_id, kind, shard_id) self.__needs_save = True...
'Merge EntityTypeInfo into aggregated type information.'
def merge(self, entity_type_info):
if self.__aggregation.merge(entity_type_info): self.__needs_save = True
'Save aggregated type information to the datastore if changed.'
def flush(self):
if self.__needs_save: def update_aggregation_tx(): aggregation = SchemaAggregationResult.load(self.__backup_id, self.__kind, self.__shard_id) if aggregation: if aggregation.merge(self.__aggregation): aggregation.put(force_writes=True) ...
'Backup entity map handler. Args: entity_proto: An instance of entity_pb.EntityProto. Yields: A serialized entity_pb.EntityProto as a string'
def map(self, entity_proto):
(yield entity_proto.SerializeToString()) (yield AggregateSchema(entity_proto))
'Restore entity map handler. Args: record: A serialized entity_pb.EntityProto. Yields: A operation.db.Put for the mapped entity'
def map(self, record):
self.initialize() pb = entity_pb.EntityProto(contents=record) if self.app_id: utils.FixKeys(pb, self.app_id) entity = datastore.Entity.FromPb(pb) if ((not self.kind_filter) or (entity.kind() in self.kind_filter)): (yield op.db.Put(entity)) if self.app_id: (yield u...
'Constructor. Args: remote_url: The URL of the remote_api handler. target_appid: The appid to intercept calls for. extra_headers: Headers to send (for authentication). normal_stub: The standard stub to delegate most calls to.'
def __init__(self, remote_url, target_appid, extra_headers, normal_stub):
self.remote_url = remote_url self.target_appid = target_appid self.extra_headers = (extra_headers or {}) if ('X-appcfg-api-version' not in self.extra_headers): self.extra_headers['X-appcfg-api-version'] = '1' self.normal_stub = normal_stub
'Creates RPC object instance. Returns: a instance of RPC.'
def CreateRPC(self):
return apiproxy_rpc.RPC(stub=self)
'Handle all calls to this stub; delegate as appropriate.'
def MakeSyncCall(self, service, call, request, response):
assert (service == 'datastore_v3') explanation = [] assert request.IsInitialized(explanation), explanation handler = getattr(self, ('_Dynamic_' + call), None) if handler: handler(request, response) else: self.normal_stub.MakeSyncCall(service, call, request, response) assert r...
'Send an RPC to a remote_api endpoint.'
def _MakeRemoteSyncCall(self, service, call, request, response):
request_pb = remote_api_pb.Request() request_pb.set_service_name(service) request_pb.set_method(call) request_pb.set_request(request.Encode()) response_pb = remote_api_pb.Response() encoded_request = request_pb.Encode() try: urlfetch_response = urlfetch.fetch(self.remote_url, encoded...
'Handle a Put request and route remotely if it matches the target app. Args: request: A datastore_pb.PutRequest response: A datastore_pb.PutResponse Raises: RemoteTransactionsUnimplemented: Remote transactions are unimplemented.'
def _Dynamic_Put(self, request, response):
if request.entity_list(): entity = request.entity(0) if (entity.has_key() and (entity.key().app() == self.target_appid)): if request.has_transaction(): raise RemoteTransactionsUnimplemented() self._MakeRemoteSyncCall('datastore_v3', 'Put', request, response) ...
'Handle AllocateIds and route remotely if it matches the target app. Args: request: A datastore_pb.AllocateIdsRequest response: A datastore_pb.AllocateIdsResponse'
def _Dynamic_AllocateIds(self, request, response):
if (request.model_key().app() == self.target_appid): self._MakeRemoteSyncCall('datastore_v3', 'AllocateIds', request, response) else: self.normal_stub.MakeSyncCall('datastore_v3', 'AllocateIds', request, response)
'Rendering method that can be called by main.py. Args: handler: the webapp2.RequestHandler invoking the method'
@classmethod def Render(cls, handler):
namespace = handler.request.get('namespace') kinds = handler.request.get_all('kind') (sizes_known, size_total, remainder) = utils.ParseKindsAndSizes(kinds) (namespace_str, kind_str) = utils.GetPrintableStrs(namespace, kinds) notreadonly_warning = capabilities.CapabilitySet('datastore_v3', capabiliti...
'Handler for get requests to datastore_admin/copy.do. Status of executed jobs is displayed.'
def get(self):
jobs = self.request.get_all('job') error = self.request.get('error', '') xsrf_error = self.request.get('xsrf_error', '') template_params = {'job_list': jobs, 'mapreduce_detail': self.MAPREDUCE_DETAIL, 'error': error, 'xsrf_error': xsrf_error, 'datastore_admin_home': utils.config.BASE_PATH} utils.Ren...
'Handler for post requests to datastore_admin/copy.do. Jobs are executed and user is redirected to the get handler.'
def post(self):
namespace = self.request.get('namespace') kinds = self.request.get_all('kind') (namespace_str, kinds_str) = utils.GetPrintableStrs(namespace, kinds) token = self.request.get('xsrf_token') remote_url = self.request.get('remote_url') extra_header = self.request.get('extra_header') jobs = [] ...
'Make exception handling overrideable by tests. In normal cases, return only the error string; do not fail to render the page for user.'
def _HandleException(self, e):
return str(e)
'Copy data map handler. Args: key: Datastore entity key or entity itself to copy. Yields: A db operation to store the entity in the target app. An operation which updates max used ID if necessary. A counter operation incrementing the count for the entity kind.'
def map(self, key):
mapper_params = get_mapper_params() target_app = mapper_params['target_app'] if isinstance(key, datastore.Entity): entity = key key = entity.key() else: entity = datastore.Get(key) entity_proto = entity._ToPb() utils.FixKeys(entity_proto, target_app) target_entity = d...
'Set up the remote API stub.'
def setup_stub(self):
if self.remote_api_stub_initialized: return params = get_mapper_params() if (('extra_header' in params) and params['extra_header']): extra_headers = dict([params['extra_header'].split(':', 1)]) else: extra_headers = {} remote_api_put_stub.configure_remote_put(params['remote_u...
'Copy data map handler. Args: key: Datastore entity key to copy. Yields: A db operation to store the entity in the target app. An operation which updates max used ID if necessary. A counter operation incrementing the count for the entity kind.'
def map(self, key):
if (not self.remote_api_stub_initialized): self.setup_stub() for op in CopyEntity.map(self, key): (yield op)
'Initialze internal state. Eval the string value and save the result. Args: value: String to compile as a regular expression. key: The YAML field name. Raises: InvalidCodeInConfiguration: if the code could not be evaluated, or the evalauted method is not callable.'
def __init__(self, value, key):
self.value = value try: self.method = eval(value, _global_temp_globals) except Exception as err: raise bulkloader_errors.InvalidCodeInConfiguration(('Invalid code for %s. Code: "%s". Details: %s' % (key, value, err))) if (not callable(self.method)): raise bul...
'Return a string representation of the method: the original string.'
def __str__(self):
return self.value
'Call the method.'
def __call__(self, *args, **kwargs):
return self.method(*args, **kwargs)
'Initialize EvaluatedCallable validator.'
def __init__(self):
super(EvaluatedCallable, self).__init__()
'Validates that the string compiles as a Python callable. Args: value: String to compile as a regular expression. key: The YAML field name. Returns: Value wrapped in an object with properties \'value\' and \'fn\'. Raises: InvalidCodeInConfiguration when value does not compile.'
def Validate(self, value, key):
if isinstance(value, self.ParsedMethod): return value else: return self.ParsedMethod(value, key)
'Returns the code string for this value.'
def ToValue(self, value):
return value.value
'Post-loading \'validation\'. Really used to fix up yaml hackyness.'
def CheckInitialized(self):
super(ConnectorOptions, self).CheckInitialized() if self.column_list: self.column_list = [str(column) for column in self.column_list]
'Check that all required (combinations) of fields are set. Also fills in computed properties. Raises: InvalidConfiguration: If the config is invalid.'
def CheckInitialized(self):
super(PropertyEntry, self).CheckInitialized() if (not (self.external_name or self.import_template or self.export)): raise bulkloader_errors.InvalidConfiguration(('Neither external_name nor import_template nor export specified for property %s.' % self.property))
'Check that all required (combinations) of fields are set. Also fills in computed properties. Raises: InvalidConfiguration: if the config is invalid.'
def CheckInitialized(self):
if ((not self.kind) and (not self.model)): raise bulkloader_errors.InvalidConfiguration('Neither kind nor model specified for transformer.') if (self.kind and self.model): raise bulkloader_errors.InvalidConfiguration('Both kind and model specified for transfor...
'Check that all required fields are set, and update global state. The imports specified in the preamble are imported at this time.'
def CheckInitialized(self):
python_import = getattr(self, 'import') topname = python_import.split('.')[0] module_name = getattr(self, 'as') if (not module_name): module_name = python_import.split('.')[(-1)] __import__(python_import, _global_temp_globals) _global_temp_globals[topname] = sys.modules[topname] _glo...
'Factory using an options dictionary. Args: options: Dictionary of options. Must contain: * xpath_to_nodes: The xpath to select a record. * style: \'element_centric\' or \'attribute_centric\' name: The name of this transformer, for use in error messages. Returns: XmlConnector connector object described by the specified...
@classmethod def create_from_options(cls, options, name):
xpath_to_nodes = options.get('xpath_to_nodes') if (not xpath_to_nodes): raise bulkloader_errors.InvalidConfiguration(('simplexml must specify xpath_to_nodes. (In transformer named %s)' % name)) if (not re.match(NODE_PATH_ONLY_RE, xpath_to_nodes)): logging.warning('simple...
'Constructor. Args: xpath_to_nodes: xpath to the nodes to run over. xml_style: ELEMENT_CENTRIC or ATTRIBUTE_CENTRIC--we\'ll either convert the list of elements to a dict (last element of the same name will be used) or the list of attributes. Raises: InvalidConfiguration: If the config is invalid.'
def __init__(self, xpath_to_nodes, xml_style):
self.xpath_to_nodes = xpath_to_nodes assert (xml_style in (self.ELEMENT_CENTRIC, self.ATTRIBUTE_CENTRIC)) self.xml_style = xml_style self.output_stream = None self.bulkload_state = None self.depth = 0 if re.match(NODE_PATH_ONLY_RE, xpath_to_nodes): self.node_list = self.xpath_to_node...
'Generator, yields dicts for nodes found as described in the options.'
def generate_import_record(self, filename, bulkload_state):
self.bulkload_state = bulkload_state tree = ElementTree.parse(filename) xpath_to_nodes = self.xpath_to_nodes if ((len(xpath_to_nodes) > 1) and (xpath_to_nodes[0] == '/') and (xpath_to_nodes[1] != '/')): if (not (tree.getroot().tag == xpath_to_nodes.split('/')[1])): return xpa...
'Initialize the output file.'
def initialize_export(self, filename, bulkload_state):
self.bulkload_state = bulkload_state if (not self.node_list): raise bulkloader_errors.InvalidConfiguration('simplexml export only supports simple /root/to/node xpath_to_nodes for now.') self.output_stream = codecs.open(filename, 'wb', 'utf-8') self.output_stream.write('<?...
'Write a dict as elements, possibly recursively.'
def write_iterable_as_elements(self, values):
if isinstance(values, dict): values = values.iteritems() for (name, value) in values: if isinstance(value, basestring): self.output_stream.write(('%s <%s>%s</%s>\n' % (self.indent, name, saxutils.escape(value), name))) else: self.output_stream.write(('%s <%s...
'Write one record for the specified entity.'
def write_dict(self, dictionary):
if (self.xml_style == self.ELEMENT_CENTRIC): self.output_stream.write(('%s<%s>\n' % (self.indent, self.entity_node))) self.write_iterable_as_elements(dictionary) self.output_stream.write(('%s</%s>\n' % (self.indent, self.entity_node))) else: self.output_stream.write(('%s<%s ' ...
'A function which returns an iterator over dictionaries. This is the only method used on import. Args: filename: The --filename argument passed in on the bulkloader command line. This value is opaque to the bulkloader and thus could specify any sort of descriptor for your generator. bulkload_state: Passed in BulkloadCo...
def generate_import_record(self, filename, bulkload_state):
raise NotImplementedError
'Initialize the output file. Args: filename: The string given as the --filename flag argument. bulkload_state: Passed in BulkloadConfig.BulkloadState object. These values are opaque to the bulkloader and thus could specify any sort of descriptor for your exporter.'
def initialize_export(self, filename, bulkload_state):
raise NotImplementedError
'Write one record for the specified entity. Args: dictionary: A post-transform dictionary.'
def write_dict(self, dictionary):
raise NotImplementedError
'Performs finalization actions after every record is written.'
def finalize_export(self):
raise NotImplementedError
'Constructor. Attributes: seen_properties: (kind, propertyname) -> number of times seen before. If seen more than once, this is a duplicate property for the kind. last_seen: Previous kind seen. If it changes, this is a new kind.'
def __init__(self):
self.seen_properties = {} self.last_seen = None
'Implementation of StatPropertyTypePropertyNameKindPostExport. See class docstring for more info. Args: instance: Input, current entity being exported. dictionary: Output, dictionary created by property_map transforms. bulkload_state: Passed bulkload_state. Returns: Dictionary--same object as passed in dictionary.'
def __call__(self, instance, dictionary, bulkload_state):
kind_name = dictionary['kind_name'] property_name = dictionary['property_name'] property_type = dictionary['property_type'] if kind_name.startswith('__'): return None if (property_type == 'NULL'): return None property_key = (kind_name, property_name) if (kind_name != self.las...
'Initialzer. Args: stream: Stream to write to. fieldnames: Fieldnames to pass to the DictWriter. encoding: Desired encoding. kwds: Additional arguments to pass to the DictWriter.'
def __init__(self, stream, fieldnames, encoding='utf-8', **kwds):
writer = codecs.getwriter(encoding) if ((writer is encodings.utf_8.StreamWriter) or (writer is encodings.ascii.StreamWriter) or (writer is encodings.latin_1.StreamWriter) or (writer is encodings.cp1252.StreamWriter)): self.no_recoding = True self.encoder = codecs.getencoder(encoding) sel...
'Wrap writerow method.'
def writerow(self, row):
row_encoded = dict([(k, self.encoder(v)[0]) for (k, v) in row.iteritems()]) self.writer.writerow(row_encoded) if self.no_recoding: return data = self.queue.getvalue() data = data.decode('utf-8') self.stream.write(data) self.queue.truncate(0)