desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Factory using an options dictionary. Args: options: Dictionary of options: columns: \'from_header\' or blank. column_list: overrides columns specifically. encoding: encoding of the file. e.g. \'utf-8\' (default), \'windows-1252\'. skip_import_header_row: True to ignore the header line on import. Defaults False, except...
@classmethod def create_from_options(cls, options, name):
column_list = options.get('column_list', None) columns = None if (not column_list): columns = options.get('columns', 'from_header') if (columns != 'from_header'): raise bulkloader_errors.InvalidConfiguration(('CSV columns must be "from_header", or a column_li...
'Initializer. Args: columns: \'from_header\' or blank column_list: overrides columns specifically. skip_import_header_row: True to ignore the header line on import. Defaults False, except must be True if columns=from_header. print_export_header_row: True to print a header line on export. Defaults to False except if col...
def __init__(self, columns, column_list, skip_import_header_row, print_export_header_row, csv_encoding=None, import_options=None, export_options=None):
self.columns = columns self.from_header = (columns == 'from_header') self.column_list = column_list self.skip_import_header_row = skip_import_header_row self.print_export_header_row = print_export_header_row self.csv_encoding = csv_encoding self.dict_generator = None self.output_stream =...
'Generator, yields dicts for nodes found as described in the options. Args: filename: Filename to read. bulkload_state: Passed bulkload_state. Yields: Neutral dict, one per row in the CSV file.'
def generate_import_record(self, filename, bulkload_state):
self.bulkload_state = bulkload_state input_stream = open(filename) input_stream = utf8_recoder(input_stream, self.csv_encoding) self.dict_generator = csv.DictReader(input_stream, self.column_list, **self.import_options) discard_line = (self.skip_import_header_row and (not self.from_header)) line...
'Initialize the output file. Args: filename: Filename to write. bulkload_state: Passed bulkload_state.'
def initialize_export(self, filename, bulkload_state):
self.bulkload_state = bulkload_state self.output_stream = open(filename, 'wb')
'Actual initialization, happens on the first entity being written.'
def __initialize_csv_writer(self, dictionary):
write_header = self.print_export_header_row if self.from_header: export_column_list = tuple(dictionary) else: export_column_list = self.column_list self.csv_writer = UnicodeDictWriter(self.output_stream, export_column_list, self.csv_encoding, **self.export_options) if write_header: ...
'Write one record for the specified entity.'
def write_dict(self, dictionary):
if (not self.csv_writer): self.__initialize_csv_writer(dictionary) self.csv_writer.writerow(dictionary)
'Constructor. Populates this Loader\'s kind and properties map. Also registers it with the bulk loader, so that all you need to do is instantiate your Loader, and the bulkload handler will automatically use it. Args: kind: a string containing the entity kind that this loader handles properties: list of (name, converter...
def __init__(self, kind, properties):
Validate(kind, basestring) self.__kind = kind Validate(properties, list) for (name, fn) in properties: Validate(name, basestring) assert callable(fn), ('Conversion function %s for property %s is not callable.' % (fn, name)) self.__properties = properties L...
'Return the entity kind that this Loader handes.'
def kind(self):
return self.__kind
'Creates an entity from a list of property values. Args: values: list/tuple of str key_name: if provided, the name for the (single) resulting Entity Returns: list of datastore.Entity The returned entities are populated with the property values from the argument, converted to native types using the properties map given ...
def CreateEntity(self, values, key_name=None):
Validate(values, (list, tuple)) assert (len(values) == len(self.__properties)), ('Expected %d CSV columns, found %d.' % (len(self.__properties), len(values))) entity = datastore.Entity(self.__kind, name=key_name) for ((name, converter), val) in zip(self.__properties, values): if (...
'Subclasses can override this to add custom entity conversion code. This is called for each entity, after its properties are populated from CSV but before it is stored. Subclasses can override this to add custom entity handling code. The entity to be inserted should be returned. If multiple entities should be inserted,...
def HandleEntity(self, entity):
return entity
'Returns a list of the Loader instances that have been created.'
@staticmethod def RegisteredLoaders():
return dict(Loader.__loaders)
'Handle a GET. Just show an info page.'
def get(self):
page = self.InfoPage(self.request.uri) self.response.out.write(page)
'Handle a POST. Reads CSV data, converts to entities, and stores them.'
def post(self):
self.response.headers['Content-Type'] = 'text/plain' (response, output) = self.Load(self.request.get(constants.KIND_PARAM), self.request.get(constants.CSV_PARAM)) self.response.set_status(response) self.response.out.write(output)
'Renders an information page with the POST endpoint and cookie flag. Args: uri: a string containing the request URI Returns: A string with the contents of the info page to be displayed'
def InfoPage(self, uri):
page = '\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html><head>\n<title>Bulk Loader</title>\n</head><body>' page += ('The bulk load endpoint is: <a href="%s">%s</a><br />\n' % (uri, uri)) coo...
'Yields a tuple of a line number and row for each row of the CSV data. Args: reader: a csv reader for the input data.'
def IterRows(self, reader):
line_num = 1 for columns in reader: (yield (line_num, columns)) line_num += 1
'Generates entities and loads them into the datastore. Returns a tuple of HTTP code and string reply. Args: iter: an iterator yielding pairs of a line number and row contents. key_format: a format string to convert a line number into an entity id. If None, then entity ID\'s are automatically generated.'
def LoadEntities(self, iter, loader, key_format=None):
entities = [] output = [] for (line_num, columns) in iter: key_name = None if (key_format is not None): key_name = (key_format % line_num) if columns: try: output.append(('\nLoading from line %d...' % line_num)) new_ent...
'Parses CSV data, uses a Loader to convert to entities, and stores them. On error, fails fast. Returns a "bad request" HTTP response code and includes the traceback in the output. Args: kind: a string containing the entity kind that this loader handles data: a string containing the CSV data to load Returns: tuple (resp...
def Load(self, kind, data):
data = data.encode('utf-8') Validate(kind, basestring) Validate(data, basestring) output = [] try: loader = Loader.RegisteredLoaders()[kind] except KeyError: output.append(('Error: no Loader defined for kind %s.' % kind)) return (httplib.BAD_REQUEST, ''....
'Factory using an options dictionary. Args: options: Dictionary of options containing: template: A Python dict-interpolation string. Required. prolog: written before the per-record output. epilog: written after the per-record output. mode: one of the following, default is \'text\' text: text file mode, newlines between...
@classmethod def create_from_options(cls, options, name):
template = options.get('template') if (not template): raise bulkloader_errors.InvalidConfiguration(('simpletext must specify template. (In transformer named %s)' % name)) prolog = options.get('prolog') epilog = options.get('epilog') mode = options.get('mode', 'text') ...
'Constructor. Args: template: A Python dict-interpolation string. prolog: written before the per-record output. epilog: written after the per-record output. mode: one of the following, default is \'text\' text: text file mode, newlines between records. nonewline: text file mode, no added newlines. binary: binary file m...
def __init__(self, template, prolog=None, epilog=None, mode='text', name=''):
if (mode not in self.VALID_MODES): raise bulkloader_errors.InvalidConfiguration(('simpletext mode must be one of "%s". (In transformer name %s.)' % ('", "'.join(self.VALID_MODES), name))) self.template = template self.prolog = prolog self.epilog = epilog self...
'Open file and write prolog.'
def initialize_export(self, filename, bulkload_state):
self.bulkload_state = bulkload_state mode = 'w' if (self.mode == 'binary'): mode = 'wb' self.export_file_pointer = open(filename, mode) if self.prolog: self.export_file_pointer.write(self.prolog) if (self.mode == 'text'): self.export_file_pointer.write('\n')
'Write one record for the specified entity.'
def write_dict(self, dictionary):
self.export_file_pointer.write((self.template % dictionary)) if (self.mode == 'text'): self.export_file_pointer.write('\n')
'Write epliog and close file after every record is written.'
def finalize_export(self):
if self.epilog: self.export_file_pointer.write(self.epilog) if (self.mode == 'text'): self.export_file_pointer.write('\n') self.export_file_pointer.close()
'Constructor. See class docstring for more info. Args: transformer_spec: A single transformer from a parsed bulkloader.yaml. This assumes that the transformer_spec is valid. It does not double check things like use_model_on_export requiring model.'
def __init__(self, transformer_spec):
self._transformer_spec = transformer_spec self._create_key = None for prop in self._transformer_spec.property_map: if (prop.property == '__key__'): self._create_key = prop
'Transform the dict to a model or entity instance(s). Args: input_dict: Neutral input dictionary describing a single input record. bulkload_state: bulkload_state object describing the state. Returns: Entity or model instance, or collection of entity or model instances, to be uploaded.'
def dict_to_entity(self, input_dict, bulkload_state):
bulkload_state_copy = copy.copy(bulkload_state) bulkload_state_copy.current_dictionary = input_dict instance = self.__create_instance(input_dict, bulkload_state_copy) bulkload_state_copy.current_instance = instance self.__run_import_transforms(input_dict, instance, bulkload_state_copy) if self._...
'Transform the entity to a dict, possibly via a model. Args: entity: An entity. bulkload_state: bulkload_state object describing the global state. Returns: A neutral output dictionary describing the record to write to the output. In the future this may return zero or multiple output dictionaries.'
def entity_to_dict(self, entity, bulkload_state):
if self._transformer_spec.use_model_on_export: instance = self._transformer_spec.model.from_entity(entity) else: instance = entity export_dict = {} bulkload_state.current_entity = entity bulkload_state.current_instance = instance bulkload_state.current_dictionary = export_dict ...
'Handle a single property on import. Args: transform: The transform spec for this property. input_dict: Neutral input dictionary describing a single input record. bulkload_state: bulkload_state object describing the global state. Returns: The value for this particular property.'
def __dict_to_prop(self, transform, input_dict, bulkload_state):
if transform.import_template: value = (transform.import_template % input_dict) else: value = input_dict.get(transform.external_name) if transform.import_transform: if transform.import_transform.supports_bulkload_state: value = transform.import_transform(value, bulkload_st...
'Return a model instance or entity from an input_dict. Args: input_dict: Neutral input dictionary describing a single input record. bulkload_state: bulkload_state object describing the global state. Returns: Entity or model instance, or collection of entity or model instances, to be uploaded.'
def __create_instance(self, input_dict, bulkload_state):
key = None if self._create_key: key = self.__dict_to_prop(self._create_key, input_dict, bulkload_state) if isinstance(key, (int, long)): key = datastore.Key.from_path(self._transformer_spec.kind, key) if self._transformer_spec.model: if isinstance(key, datastore.K...
'Fill in a single entity or model instance from an input_dict. Args: input_dict: Input dict from the connector object. instance: Entity or model instance to fill in. bulkload_state: Passed bulkload state.'
def __run_import_transforms(self, input_dict, instance, bulkload_state):
for transform in self._transformer_spec.property_map: if (transform.property == '__key__'): continue value = self.__dict_to_prop(transform, input_dict, bulkload_state) if self._transformer_spec.model: setattr(instance, transform.property, value) else: ...
'Transform a single export-side field value to dict property. Args: value: Value from the entity or model instance. property_name: Name of the value in the entity or model instance. transform: Transform property, either an ExportEntry or PropertyEntry export_dict: output dictionary. bulkload_state: Passed bulkload stat...
def __prop_to_dict(self, value, property_name, transform, export_dict, bulkload_state):
if transform.export_transform: try: if transform.export_transform.supports_bulkload_state: transformed_value = transform.export_transform(value, bulkload_state=bulkload_state) else: transformed_value = transform.export_transform(value) except E...
'Fill in export_dict for an entity or model instance. Args: instance: Entity or model instance export_dict: output dictionary. bulkload_state: Passed bulkload state.'
def __run_export_transforms(self, instance, export_dict, bulkload_state):
for transform in self._transformer_spec.property_map: if (transform.property == '__key__'): value = instance.key() elif self._transformer_spec.use_model_on_export: value = getattr(instance, transform.property, transform.default_value) else: value = instanc...
'Constructor. Args: import_record_iterator: Method which yields neutral dictionaries. dict_to_entity: Method dict_to_entity(input_dict) returns model or entity instance(s). name: Name to register with the bulkloader importers (as \'kind\'). increment_id: Method IncrementId(key) which will increment the auto-allocated i...
def __init__(self, import_record_iterator, dict_to_entity, name, increment_id):
self.import_record_iterator = import_record_iterator self.dict_to_entity = dict_to_entity self.kind = name self.bulkload_state = BulkloadState() self.increment_id = increment_id self.high_ids = {}
'Required as part of the bulkloader Loader interface. At the moment, this is not actually used by the bulkloader for import; instead we will allocate IDs if necessary in finalize. Returns: dict {ancestor_path : {kind : id}} of high id values, curently always {}.'
def get_high_ids(self):
return {}
'Performs initialization. Merely records the values for later use. Args: filename: The string given as the --filename flag argument. loader_opts: The string given as the --loader_opts flag argument.'
def initialize(self, filename, loader_opts):
self.bulkload_state.loader_opts = loader_opts self.bulkload_state.filename = filename
'Performs finalization actions after the upload completes. If keys with numeric ids were used on import, this will call AllocateIds to ensure that autogenerated IDs will not raise exceptions on conflict with uploaded entities.'
def finalize(self):
if self.increment_id: for (path, high_id) in self.high_ids.iteritems(): high_id_key = datastore.Key.from_path(*(path + (high_id,))) self.increment_id(high_id_key)
'Iterator yielding neutral dictionaries from the connector object. Args: filename: Filename argument passed in on the command line. Returns: Iterator yielding neutral dictionaries, later passed to create_entity.'
def generate_records(self, filename):
return self.import_record_iterator(filename, self.bulkload_state)
'Bulkloader method to generate keys, mostly unused here. This is called by the bulkloader just before it calls create_entity. The line_number is returned to be passed to the record dict, but otherwise unused. Args: line_number: Record number from the bulkloader. unused_values: Neutral dict from generate_records; unused...
def generate_key(self, line_number, unused_values):
return line_number
'Check the entity to see it has a numeric ID higher than any seen so far. High IDs are stored in self.high_ids[path-to-entity-kind]. They are not tracked if self.increment_id is None. Args: entity: An entity with a key.'
def __track_max_id(self, entity):
if (not self.increment_id): return if isinstance(entity, datastore.Entity): if (not entity.key()): return elif (not entity.has_key()): return key = entity.key() key_id = key.id() if (not key_id): return path = tuple(key.to_path()[:(-1)]) if (se...
'Creates entity/entities from input values via the dict_to_entity method. Args: values: Neutral dict from generate_records. key_name: record number from generate_key. parent: Always None in this implementation of a Loader. Returns: Entity or model instance, or collection of entity or model instances, to be uploaded.'
def create_entity(self, values, key_name=None, parent=None):
input_dict = values input_dict['__record_number__'] = key_name entity = self.dict_to_entity(input_dict, self.bulkload_state) self.__track_max_id(entity) return entity
'Constructor. Args: export_recorder: Object which writes results, an implementation of ConnectorInterface. entity_to_dict: Method which converts a single entity to a neutral dict. kind: Kind to identify this object to the bulkloader. sort_key_from_entity: Optional method to return a sort key for each entity. This key w...
def __init__(self, export_recorder, entity_to_dict, kind, sort_key_from_entity):
self.export_recorder = export_recorder self.entity_to_dict = entity_to_dict self.kind = kind self.sort_key_from_entity = sort_key_from_entity self.calculate_sort_key_from_entity = bool(sort_key_from_entity) self.bulkload_state = BulkloadState()
'Performs initialization and validation of the output file. Args: filename: The string given as the --filename flag argument. exporter_opts: The string given as the --exporter_opts flag argument.'
def initialize(self, filename, exporter_opts):
self.bulkload_state.filename = filename self.bulkload_state.exporter_opts = exporter_opts self.export_recorder.initialize_export(filename, self.bulkload_state)
'Outputs the downloaded entities. Args: entity_iterator: An iterator that yields the downloaded entities in sorted order.'
def output_entities(self, entity_iterator):
for entity in entity_iterator: output_dict = self.entity_to_dict(entity, self.bulkload_state) if output_dict: self.export_recorder.write_dict(output_dict)
'Performs finalization actions after the download completes.'
def finalize(self):
self.export_recorder.finalize_export()
'Returns the base path of this admin app, which is chosen by the user. The user specifies which paths map to this application in their app.cfg. You can get that base path with this method. Combine with the constant paths specified by the classes to construct URLs.'
def base_path(self):
path = self.__class__.PATH return self.request.path[:(- len(path))]
'Filters the current URL to only have the given list of arguments. For example, if your URL is /search?q=foo&num=100&start=10, then self.filter_url([\'start\', \'num\']) => /search?num=100&start=10 self.filter_url([\'q\']) => /search?q=10 self.filter_url([\'random\']) => /search?'
def filter_url(self, args):
queries = [] for arg in args: value = self.request.get(arg) if value: queries.append(((arg + '=') + urllib.quote_plus(ustr(self.request.get(arg))))) return ((self.request.path + '?') + '&'.join(queries))
'Detects if app is running in production. Returns a boolean.'
def in_production(self):
server_software = os.getenv('SERVER_SOFTWARE') if (server_software is None): return False return (not server_software.startswith('Development'))
'Shows template displaying the configured cron jobs.'
def get(self, now=None):
if (not now): now = datetime.datetime.utcnow() values = {'request': self.request} cron_info = _ParseCronYaml() values['cronjobs'] = [] values['now'] = str(now) if (cron_info and cron_info.cron): for entry in cron_info.cron: job = {} values['cronjobs'].appe...
'Shows template displaying the XMPP.'
def get(self):
xmpp_configured = True values = {'xmpp_configured': xmpp_configured, 'request': self.request} self.generate('xmpp.html', values)
'Shows template displaying the Inbound Mail form.'
def get(self):
inboundmail_configured = True values = {'inboundmail_configured': inboundmail_configured, 'request': self.request} self.generate('inboundmail.html', values)
'Make a synchronous taskqueue api call. Args: rpc_name: The name of the rpc to call. request: The protocol buffer to be used as the request. Returns: The rpc response. This is an instance of the correct response protocol buffer for the request \'rpc_name\'.'
def _make_sync_call(self, rpc_name, request):
response = getattr(taskqueue_service_pb, ('TaskQueue%sResponse' % rpc_name))() apiproxy_stub_map.MakeSyncCall('taskqueue', rpc_name, request, response) return response
'Get a list of queue in the application. Args: now: The current time. A datetime.datetime object with a utc timezone. Returns: A list of queue dicts corresponding to the tasks for this application.'
def get_queues(self, now):
request = taskqueue_service_pb.TaskQueueFetchQueuesRequest() request.set_max_rows(1000) response = self._make_sync_call('FetchQueues', request) queue_stats_request = taskqueue_service_pb.TaskQueueFetchQueueStatsRequest() queue_stats_request.set_max_num_tasks(0) queues = [] for queue_proto in...
'Returns the number of tasks in the named queue. Args: queue_name: The name of the queue. Returns: The number of tasks in the queue.'
def get_number_tasks_in_queue(self, queue_name):
queue_stats_request = taskqueue_service_pb.TaskQueueFetchQueueStatsRequest() queue_stats_request.set_max_num_tasks(0) queue_stats_request.add_queue_name(queue_name) queue_stats_response = self._make_sync_call('FetchQueueStats', queue_stats_request) assert (queue_stats_response.queuestats_size() == 1...
'Fetch the specified tasks from taskqueue. Note: This only searchs by eta. Args: now: The current time. This is used to calculate the EtaFromNow. Must be a datetime.datetime in the utc timezone. queue_name: The queue to search for tasks. start_eta_usec: The earliest eta to return. start_task_name: For tasks with the sa...
def get_tasks(self, now, queue_name, start_eta_usec, start_task_name, num_tasks):
request = taskqueue_service_pb.TaskQueueQueryTasksRequest() request.set_queue_name(queue_name) request.set_start_task_name(start_task_name) request.set_start_eta_usec(start_eta_usec) request.set_max_rows(num_tasks) response = self._make_sync_call('QueryTasks', request) tasks = [] for tas...
'Delete the named task. Args: queue_name: The name of the queue. task_name: The name of the task.'
def delete_task(self, queue_name, task_name):
request = taskqueue_service_pb.TaskQueueDeleteRequest() request.set_queue_name(queue_name) request.task_name_list().append(task_name) self._make_sync_call('Delete', request)
'Purge the named queue. Args: queue_name: the name of the queue.'
def purge_queue(self, queue_name):
request = taskqueue_service_pb.TaskQueuePurgeQueueRequest() request.set_queue_name(queue_name) self._make_sync_call('PurgeQueue', request)
'Shows template displaying the configured task queues.'
def get(self):
def is_push_queue(queue): return (queue['mode'] == QUEUE_MODE.PUSH) def is_pull_queue(queue): return (queue['mode'] == QUEUE_MODE.PULL) now = datetime.datetime.utcnow() values = {} try: queues = self.helper.get_queues(now) push_queues = QueueBatch('Push Queues', Tr...
'Handle modifying actions and/or redirect to GET page.'
@xsrf_required def post(self):
queue_name = self.request.get('queue') if self.request.get('action:purgequeue'): self.helper.purge_queue(queue_name) self.redirect(self.request.path_url)
'Parse the arguments passed into the request and store them on self.'
def parse_arguments(self):
self.queue_name = self.request.get('queue') self.start_name = self.request.get('start_name', '') self.start_eta = int(self.request.get('start_eta', '0')) self.per_page = int(self.request.get('per_page', self.PAGE_SIZE)) self.page_no = int(self.request.get('page_no', '1')) assert (self.per_page >...
'Perform a redirect to the tasks page. Args: keep_offset: If true, will keep the \'start_eta\', \'start_name\' and \'page_no\' fields.'
def redirect_to_tasks(self, keep_offset=True):
params = {'queue': self.queue_name, 'per_page': self.per_page} if keep_offset: params['start_name'] = self.start_name params['start_eta'] = self.start_eta params['page_no'] = self.page_no self.redirect(('%s?%s' % (self.request.path, urllib.urlencode(params))))
'Generate the params for a page link.'
def _generate_page_params(self, page_dict):
params = [('queue', self.queue_name), ('start_eta', page_dict['start_eta']), ('start_name', page_dict['start_name']), ('per_page', self.per_page), ('page_no', page_dict['number'])] return urllib.urlencode(params)
'Generate the page dicts from a list of tasks. Args: tasks: A list of task dicts, sorted by eta. Returns: A list of page dicts containing the following keys: \'start_name\', \'start_eta\', \'number\', \'has_gap\'.'
def generate_page_dicts(self, start_tasks, end_tasks):
page_map = {} for (i, task) in enumerate(start_tasks[::self.per_page]): page_no = (i + 1) page_map[page_no] = {'start_name': task['name'], 'start_eta': task['eta_usec'], 'number': page_no} if (page_map and (page_no < (self.page_no - 1))): page_map[page_no]['has_gap'] = True for (...
'Shows template displaying the queue\'s tasks.'
def get(self):
self.parse_arguments() now = datetime.datetime.utcnow() tasks_to_fetch = min(self.MAX_TASKS_TO_FETCH, max(self.MIN_TASKS_TO_FETCH, (self.per_page * 10))) try: tasks = self.helper.get_tasks(now, self.queue_name, self.start_eta, self.start_name, tasks_to_fetch) except apiproxy_errors.Applicati...
'Shows template displaying the app\'s backends or a single backend.'
def get(self):
backend_name = self.request.get('backendName') if backend_name: return self.render_backend_page(backend_name) else: return self.render_backends_page()
'Shows template displaying all the app\'s backends.'
def render_backends_page(self):
if hasattr(self.stub, 'get_backend_info'): backend_info = (self.stub.get_backend_info() or []) else: backend_info = [] backend_list = [] for backend in backend_info: backend_list.append({'name': backend.name, 'instances': backend.instances, 'instanceclass': (backend.get_class() o...
'Get the BackendEntry for a single backend.'
def get_backend_entry(self, backend_name):
if (not hasattr(self.stub, 'get_backend_info')): return None backend_entries = (self.stub.get_backend_info() or []) for backend in backend_entries: if (backend.name == backend_name): return backend return None
'Shows template displaying a single backend.'
def render_backend_page(self, backend_name):
backend = self.get_backend_entry(backend_name) instances = [] if backend: for i in range(backend.instances): instances.append({'id': i, 'address': backends.get_hostname(backend_name, i), 'state': 'running'}) values = {'request': self.request, 'backend_name': backend_name, 'backend_pa...
'Convert string to boolean value. Args: string_value: A string. Returns: Boolean. True if string_value is "true", False if string_value is "false". This is case-insensitive. Raises: ValueError: string_value not "true" or "false".'
@staticmethod def _ToBool(string_value):
string_value_low = string_value.lower() if (string_value_low not in ('false', 'true')): raise ValueError(('invalid literal for boolean: %s' % string_value)) return (string_value_low == 'true')
'Fetch value from memcache and detect its type. Args: key: String Returns: (value, type), value is a Python object or None if the key was not set in the cache, type is a string describing the type of the value.'
def _GetValueAndType(self, key):
try: value = memcache.get(key) except (pickle.UnpicklingError, AttributeError, EOFError, ImportError, IndexError) as e: msg = ('Failed to retrieve value from cache: %s' % e) return (msg, 'error') if (value is None): return (None, self.DEFAULT_TYPESTR_FOR_NEW...
'Convert a string value and store the result in memcache. Args: key: String type_: String, describing what type the value should have in the cache. value: String, will be converted according to type_. Returns: Result of memcache.set(key, converted_value). True if value was set. Raises: ValueError: Value can\'t be conv...
def _SetValue(self, key, type_, value):
for (_, converter, typestr) in self.TYPES: if (typestr == type_): value = converter(value) break else: raise ValueError(('Type %s not supported.' % type_)) return memcache.set(key, value)
'Show template and prepare stats and/or key+value to display/edit.'
def get(self):
values = {'request': self.request, 'message': self.request.get('message')} edit = self.request.get('edit') key = self.request.get('key') if edit: key = edit values['show_stats'] = False values['show_value'] = False values['show_valueform'] = True values['types'] =...
'Encode a dictionary into a URL query string. In contrast to urllib this encodes unicode characters as UTF8. Args: query: Dictionary of key/value pairs. Returns: String.'
def _urlencode(self, query):
return '&'.join((('%s=%s' % (urllib.quote_plus(k.encode('utf8')), urllib.quote_plus(v.encode('utf8')))) for (k, v) in query.iteritems()))
'Handle modifying actions and/or redirect to GET page.'
@xsrf_required def post(self):
next_param = {} if self.request.get('action:flush'): if memcache.flush_all(): next_param['message'] = 'Cache flushed, all keys dropped.' else: next_param['message'] = 'Flushing the cache failed. Please try again.' elif self.request.ge...
'Returns the santized "start" argument from the URL.'
def start(self):
return self.request.get_range('start', min_value=0, default=0)
'Returns the sanitized "num" argument from the URL.'
def num(self):
return self.request.get_range('num', min_value=1, max_value=100, default=10)
'Parses the URL arguments and executes the query. Args: start: How many entities from the beginning of the result list should be skipped from the query. num: How many entities should be returned, if 0 (default) then a reasonable default will be chosen. Returns: A tuple (list of entities, total entity count). If inappr...
def execute_query(self, start=0, num=0, no_order=False):
kind = self.request.get('kind') namespace = self.request.get('namespace') if (not namespace): namespace = None if (not kind): return ([], 0) query = datastore.Query(kind, _namespace=namespace) order = self.request.get('order') order_type = self.request.get('order_type') i...
'Returns the union of key names used by the given list of entities. We return the union as a dictionary mapping the key names to a sample value from one of the entities for the key name.'
def get_key_values(self, entities):
key_dict = {} for entity in entities: for (key, value) in entity.iteritems(): if key_dict.has_key(key): key_dict[key].append(value) else: key_dict[key] = [value] return key_dict
'Redirect to the \'next\' url with message added as the msg parameter.'
def redirect_with_message(self, message):
quoted_message = urllib.quote_plus(message) redirect_url = self.request.get('next') if ('?' in redirect_url): redirect_url += ('&msg=%s' % quoted_message) else: redirect_url += ('?msg=%s' % quoted_message) self.redirect(redirect_url)
'Get sorted list of kind names the datastore knows about. This should only be called in the development environment as metadata queries are expensive and no caching is done. Args: namespace: The namespace to fetch the schema for e.g. \'google.com\'. It is an error to pass in None. Returns: A sorted list of kinds e.g. [...
def get_kinds(self, namespace):
assert (namespace is not None) q = metadata.Kind.all(namespace=namespace) return [x.kind_name.encode('utf-8') for x in q.run()]
'Formats the results from execute_query() for datastore.html. The only complex part of that process is calculating the pager variables to generate the Gooooogle pager at the bottom of the page.'
def get(self):
(result_set, total) = self.execute_query() key_values = self.get_key_values(result_set) keys = key_values.keys() keys.sort() headers = [] for key in keys[:DEFAULT_MAX_DATASTORE_VIEWER_COLUMNS]: sample_value = key_values[key][0] headers.append({'name': ustr(key), 'type': DataType....
'Handle POST.'
@xsrf_required def post(self):
if self.request.get('flush_memcache'): if memcache.flush_all(): message = 'Cache flushed, all keys dropped.' else: message = 'Flushing the cache failed. Please try again.' self.redirect_with_message(message) return kind = ...
'Shows Datastore Stats generator button.'
def get(self):
values = {'request': self.request, 'app_id': self.request.get('app_id', None), 'status': self.request.get('status', None), 'msg': self.request.get('msg', None)} self.generate('datastore_stats.html', values)
'Handle actions and redirect to GET page.'
@xsrf_required def post(self):
app_id = self.request.get('app_id', None) if self.request.get('action:compute_stats'): status = 'OK' msg = self.generate_stats(_app=app_id) else: status = 'FAIL' msg = 'No processing requested' uri = self.request.path_url self.redirect(('%s?%s' % (uri, urllib.ur...
'Generate datastore stats.'
def generate_stats(self, _app=None):
processor = datastore_stats_generator.DatastoreStatsProcessor(_app) return processor.Run().Report()
'Displays list of FTS indexes.'
def get(self):
start = self.request.get_range('start', min_value=0, default=0) limit = self.request.get_range('num', min_value=1, max_value=100, default=10) namespace = self.request.get('namespace', default_value=None) resp = search.get_indexes(offset=start, limit=(limit + 1), namespace=(namespace or '')) has_more...
'Format document list and produce corresponding hdf representation.'
def _ProcessSearchResponse(self, response):
documents = [] field_names = set() for result in response.results: doc = Document(result.doc_id) for field in result.fields: field_names.add(field.name) doc.fields[field.name] = field documents.append(doc) field_names = sorted(field_names) docs = [] ...
'Displays documents in a FTS index.'
def get(self):
start = self.request.get_range('start', min_value=0, default=0) query = self.request.get('query') namespace = self.request.get('namespace') limit = self.request.get_range('num', min_value=1, max_value=100, default=10) index_name = (self.request.get('index') or 'index') index = search.Index(name=...
'Displays FTS document.'
def get(self):
index_name = self.request.get('index') doc_id = self.request.get('id') namespace = self.request.get('namespace') doc = None index = search.Index(name=index_name, namespace=namespace) resp = index.get_range(start_id=doc_id, limit=1) if (resp.results and (resp.results[0].doc_id == doc_id)): ...
'Handle POST.'
@xsrf_required def post(self):
index_name = self.request.get('index') namespace = self.request.get('namespace') docs = [] index = 0 num_docs = int(self.request.get('numdocs')) for i in xrange(1, (num_docs + 1)): key = self.request.get(('doc%d' % i)) if key: docs.append(key) index = search.Index...
'Constructor. May be called as a copy constructor. If kind_or_entity is a datastore.Entity, copies it into this Entity. datastore.Get() and Query() returns instances of datastore.Entity, so this is useful for converting them back to SearchableEntity so that they\'ll be indexed when they\'re stored back in the datastore...
def __init__(self, kind_or_entity, word_delimiter_regex=None, *args, **kwargs):
self._word_delimiter_regex = word_delimiter_regex if isinstance(kind_or_entity, datastore.Entity): self._Entity__key = kind_or_entity._Entity__key self._Entity__unindexed_properties = frozenset(kind_or_entity.unindexed_properties()) if isinstance(kind_or_entity, SearchableEntity): ...
'Rebuilds the full text index, then delegates to the superclass. Returns: entity_pb.Entity'
def _ToPb(self, *args, **kwargs):
for properties_to_index in self._searchable_properties: index_property_name = SearchableEntity.IndexPropertyName(properties_to_index) if (index_property_name in self): del self[index_property_name] if (not properties_to_index): properties_to_index = self.keys() ...
'Returns a set of keywords appropriate for full text indexing. See SearchableQuery.Search() for details. Args: text: string Returns: set of strings'
@classmethod def _FullTextIndex(cls, text, word_delimiter_regex=None):
if (word_delimiter_regex is None): word_delimiter_regex = cls._word_delimiter_regex if text: datastore_types.ValidateString(text, 'text', max_len=sys.maxint) text = word_delimiter_regex.sub(' ', text) words = text.lower().split() words = set((unicode(w) for w in words)...
'Given index definition, returns the name of the property to put it in.'
@classmethod def IndexPropertyName(cls, properties):
name = SearchableEntity._FULL_TEXT_INDEX_PROPERTY if properties: name += ('_' + '_'.join(properties)) return name
'Add a search query. This may be combined with filters. Note that keywords in the search query will be silently dropped if they are stop words or too short, ie if they wouldn\'t be indexed. Args: search_query: string Returns: # this query SearchableQuery'
def Search(self, search_query, word_delimiter_regex=None, properties=ALL_PROPERTIES):
datastore_types.ValidateString(search_query, 'search query') self._search_query = search_query self._word_delimiter_regex = word_delimiter_regex self._properties = properties return self
'Adds filters for the search query, then delegates to the superclass. Mimics Query.GetFilterPredicate()\'s signature. Raises BadFilterError if a filter on the index property already exists. Returns: datastore_query.FilterPredicate'
def GetFilterPredicate(self, *args, **kwds):
properties = getattr(self, '_properties', ALL_PROPERTIES) index_property_name = SearchableEntity.IndexPropertyName(properties) if (index_property_name in self): raise datastore_errors.BadFilterError(('%s is a reserved name.' % index_property_name)) filter = super(SearchableQuery, sel...
'Add a search query, by trying to add it to all subqueries. Args: args: Passed to Search on each subquery. kwargs: Passed to Search on each subquery. Returns: self for consistency with SearchableQuery.'
def Search(self, *args, **kwargs):
for q in self: q.Search(*args, **kwargs) return self
'Adds a full text search to this query. Args: search_query, a string containing the full text search query. Returns: self'
def search(self, search_query, properties=ALL_PROPERTIES):
self._search_query = search_query self._properties = properties if (self._properties not in getattr(self, '_searchable_properties', [ALL_PROPERTIES])): raise datastore_errors.BadFilterError(('%s does not have a corresponding index. Please add it tothe SEARCHABLE_PROP...
'Wraps db.Query._get_query() and injects SearchableQuery.'
def _get_query(self):
query = db.Query._get_query(self, _query_class=SearchableQuery, _multi_query_class=SearchableMultiQuery) if self._search_query: query.Search(self._search_query, properties=self._properties) return query
'Wraps db.Model._populate_internal_entity() and injects SearchableEntity.'
def _populate_internal_entity(self):
entity = db.Model._populate_internal_entity(self, _entity_class=SearchableEntity) entity._searchable_properties = self.SearchableProperties() return entity
'Wraps db.Model.from_entity() and injects SearchableEntity.'
@classmethod def from_entity(cls, entity):
if (not isinstance(entity, SearchableEntity)): entity = SearchableEntity(entity) return super(SearchableModel, cls).from_entity(entity)
'Returns a SearchableModel.Query for this kind.'
@classmethod def all(cls):
query = SearchableModel.Query(cls) query._searchable_properties = cls.SearchableProperties() return query
'Return a bool indicating whether we should record this request. Args: env: The CGI or WSGI environment dict. Returns: True if this request should be recorded, False if not. The default implementation returns True iff the request matches FILTER_LIST (see above) *and* random.random() < RECORD_FRACTION.'
def should_record(env):
if config.FILTER_LIST: if config.DEBUG: logging.debug('FILTER_LIST: %r', config.FILTER_LIST) for filter_dict in config.FILTER_LIST: for (key, regex) in filter_dict.iteritems(): negated = (isinstance(regex, str) and regex.startswith('!')) if ...