desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Transform a path to a canonical key for that path. Args: path: A string, e.g. \'/foo/bar/12345\'. Returns: A string derived from path, e.g. \'/foo/bar/X\'.'
def normalize_path(path):
return path
'Extract a canonical key from a StatsProto instance. This default implementation calls config.normalize_path() on the path returned by request.http_path(), and then prepends the HTTP method and a space, unless the method is \'GET\', in which case the method and the space are omitted (so as to display a more compact key...
def extract_key(request):
key = config.normalize_path(request.http_path()) if (request.http_method() != 'GET'): key = ('%s %s' % (request.http_method(), key)) return key
'Constructor. Args: env: A dict giving the CGI or WSGI environment.'
def __init__(self, env):
self.env = dict((kv for kv in env.iteritems() if isinstance(kv[1], str))) self.start_timestamp = time.time() self.http_status = 0 self.end_timestamp = self.start_timestamp self.traces = [] self.pending = {} self.overhead = (time.time() - self.start_timestamp) self._lock = threading.Lock(...
'Return the request method, e.g. \'GET\' or \'POST\'.'
def http_method(self):
return self.env.get('REQUEST_METHOD', 'GET')
'Return the request path, e.g. \'/\' or \'/foo/bar\', excluding the query.'
def http_path(self):
return self.env.get('PATH_INFO', '')
'Return the query string, if any, with \'?\' prefix. If there is no query string, an empty string is returned (i.e. not \'?\').'
def http_query(self):
query_string = self.env.get('QUERY_STRING', '') if query_string: query_string = ('?' + query_string) return query_string
'Record a custom event. Args: label: A string to use as event label; a \'custom.\' prefix will be added. data: Optional value to record. This can be anything; the value will be formatted using format_value() before it is recorded.'
def record_custom_event(self, label, data=None):
pre_now = time.time() sreq = format_value(data) now = time.time() delta = int((1000 * (now - self.start_timestamp))) trace = datamodel_pb.IndividualRpcStatsProto() self.get_call_stack(trace) trace.set_service_call_name(('custom.' + label)) trace.set_request_data_summary(sreq) trace.s...
'Records additional information relating to datastore RPCs. Parses requests and responses of datastore related RPCs, and records the primary keys of entities that are put into the datastore or fetched from the datastore. Non-datastore RPCs are ignored. Keys are recorded in the form of Reference protos. Currently the in...
def record_datastore_details(self, call, request, response, trace):
if (call == 'Put'): self.record_put_details(response, trace) elif (call == 'Delete'): self.record_delete_details(response, trace) elif (call == 'Commit'): self.record_commit_details(response, trace) elif (call in ('RunQuery', 'Next')): self.record_query_details(call, requ...
'Records additional put details based on config options. Details include: Keys of entities written and cost information for the Put RPC. Args: response: The response protocol message of the Put RPC call. trace: IndividualStatsProto where information must be recorded.'
def record_put_details(self, response, trace):
if config.DATASTORE_DETAILS: details = trace.mutable_datastore_details() for key in response.key_list(): newent = details.add_keys_written() newent.CopyFrom(key) if config.CALC_RPC_COSTS: writes = (response.cost().entity_writes() + response.cost().index_writes()) ...
'Records cost information for the Delete RPC. Args: response: The response protocol message of the Delete RPC call. trace: IndividualStatsProto where information must be recorded.'
def record_delete_details(self, response, trace):
if config.CALC_RPC_COSTS: writes = (response.cost().entity_writes() + response.cost().index_writes()) trace.set_call_cost_microdollars((writes * config.DATASTORE_WRITE_OP_COST)) _add_billed_op_to_trace(trace, writes, datamodel_pb.BilledOpProto.DATASTORE_WRITE)
'Records cost information for the Commit RPC. Args: response: The response protocol message of the Commit RPC call. trace: IndividualStatsProto where information must be recorded.'
def record_commit_details(self, response, trace):
if config.CALC_RPC_COSTS: cost = response.cost() writes = ((cost.commitcost().requested_entity_puts() + cost.commitcost().requested_entity_deletes()) + cost.index_writes()) trace.set_call_cost_microdollars((writes * config.DATASTORE_WRITE_OP_COST)) _add_billed_op_to_trace(trace, writ...
'Records additional get details based on config options. Details include: Keys of entities requested, whether or not the requested key was successfully fetched, and cost information for the Get RPC. Args: request: The request protocol message of the Get RPC call. response: The response protocol message of the Get RPC c...
def record_get_details(self, request, response, trace):
if config.DATASTORE_DETAILS: details = trace.mutable_datastore_details() for key in request.key_list(): newent = details.add_keys_read() newent.CopyFrom(key) for entity_present in response.entity_list(): details.add_get_successful_fetch(entity_present.has_...
'Records additional query details based on config options. Details include: Keys of entities fetched by a datastore query and cost information. Information is recorded for both the RunQuery and Next calls. For RunQuery calls, we record the entity kind and ancestor (if applicable) and cursor information (which can help ...
def record_query_details(self, call, request, response, trace):
details = trace.mutable_datastore_details() if (not response.keys_only()): for entity in response.result_list(): newent = details.add_keys_read() newent.CopyFrom(entity.key()) if (call == 'RunQuery'): if config.DATASTORE_DETAILS: if request.has_kind(): ...
'Records cost information for the AllocateIds RPC. Args: trace: IndividualStatsProto where information must be recorded.'
def record_allocate_ids_details(self, trace):
trace.set_call_cost_microdollars(config.DATASTORE_SMALL_OP_COST) _add_billed_op_to_trace(trace, 1, datamodel_pb.BilledOpProto.DATASTORE_SMALL)
'Records information relating to xmpp RPCs. Args: call: The call name, e.g. \'SendMessage\'. request: The request protocol message corresponding to the call. trace: IndividualStatsProto where information must be recorded.'
def record_xmpp_details(self, call, request, trace):
stanzas = 0 if (call == 'SendMessage'): stanzas = request.jid_size() elif (call in ('GetPresence', 'SendPresence', 'SendInvite')): stanzas = 1 trace.set_call_cost_microdollars((stanzas * config.XMPP_STANZA_COST)) _add_billed_op_to_trace(trace, stanzas, datamodel_pb.BilledOpProto.XMPP...
'Records information relating to channel RPCs. Args: call: The call name, e.g. \'CreateChannel\'. trace: IndividualStatsProto where information must be recorded.'
def record_channel_details(self, call, trace):
if (call == 'CreateChannel'): trace.set_call_cost_microdollars(config.CHANNEL_CREATE_COST) _add_billed_op_to_trace(trace, 1, datamodel_pb.BilledOpProto.CHANNEL_OPEN) elif (call == 'GetPresence'): trace.set_call_cost_microdollars(config.CHANNEL_PRESENCE_COST) _add_billed_op_to_tra...
'Records information relating to mail RPCs. Args: call: The call name, e.g. \'Send\'. request: The request protocol message corresponding to the call. trace: IndividualStatsProto where information must be recorded.'
def record_mail_details(self, call, request, trace):
if (call in ('Send', 'SendToAdmin')): num_recipients = ((request.to_size() + request.cc_size()) + request.bcc_size()) trace.set_call_cost_microdollars((config.MAIL_RECIPIENT_COST * num_recipients)) _add_billed_op_to_trace(trace, num_recipients, datamodel_pb.BilledOpProto.MAIL_RECIPIENT)
'Record the request of an RPC call. Args: service: The service name, e.g. \'memcache\'. call: The call name, e.g. \'Get\'. request: The request object. response: The response object (ignored). rpc: The RPC object; may be None.'
def record_rpc_request(self, service, call, request, response, rpc):
pre_now = time.time() sreq = format_value(request) now = time.time() delta = int((1000 * (now - self.start_timestamp))) trace = datamodel_pb.IndividualRpcStatsProto() self.get_call_stack(trace) trace.set_service_call_name(('%s.%s' % (service, call))) trace.set_request_data_summary(sreq) ...
'Record the response of an RPC call. Args: service: The service name, e.g. \'memcache\'. call: The call name, e.g. \'Get\'. request: The request object. response: The response object (ignored). rpc: The RPC object; may be None. This first tries to match the request with an unmatched request trace. If no matching reques...
def record_rpc_response(self, service, call, request, response, rpc):
now = time.time() key = ('%s.%s' % (service, call)) delta = int((1000 * (now - self.start_timestamp))) sresp = format_value(response) if (rpc is not None): with self._lock: index = self.pending.get(rpc) if (index is not None): del self.pending[rpc] ...
'Record the HTTP status code and the end time of the HTTP request.'
def record_http_status(self, status):
try: self.http_status = int(status) except (ValueError, TypeError): self.http_status = 0 self.end_timestamp = time.time()
'Save the recorded data to memcache and log some info. This wraps the _save() method, which does the actual work; this function just logs the total time it took and some other statistics.'
def save(self):
t0 = time.time() with self._lock: num_pending = len(self.pending) if num_pending: logging.warn('Found %d RPC request(s) without matching response (presumably due to timeouts or other errors)', num_pending) self.dump() try: (key, len_part...
'Internal function to save the recorded data to memcache. Returns: A tuple (key, summary_size, full_size).'
def _save(self):
(part, full) = self.get_both_protos_encoded() key = make_key(self.start_timestamp) errors = memcache.set_multi({config.PART_SUFFIX: part, config.FULL_SUFFIX: full}, time=(36 * 3600), key_prefix=key, namespace=config.KEY_NAMESPACE) if errors: logging.warn('Memcache set_multi() error: %s'...
'Return a string representing all recorded info an encoded protobuf. This constructs the full proto and calls its .Encode() method; if the resulting string is too large, it tries a number of increasingly aggressive strategies for chopping the data down.'
def get_both_protos_encoded(self):
proto = self.get_summary_proto() part_encoded = proto.Encode() self.add_full_info_to_proto(proto) full_encoded = proto.Encode() if (len(full_encoded) <= memcache.MAX_VALUE_SIZE): return (part_encoded, full_encoded) if (config.MAX_LOCALS > 0): for trace in proto.individual_stats_l...
'Update a protobuf representing with additional data.'
def add_full_info_to_proto(self, proto):
user_email = self.env.get('USER_EMAIL') if user_email: proto.set_user_email(user_email) if (self.env.get('USER_IS_ADMIN') == '1'): proto.set_is_admin(True) for (key, value) in sorted(self.env.iteritems()): x = proto.add_cgi_env() x.set_key(key) x.set_value(value) ...
'Return the full protobuf, wrapped in a StatsProto.'
def get_full_proto(self):
proto = self.get_summary_proto() self.add_full_info_to_proto(proto) return StatsProto(proto)
'Return a string representing a summary an encoded protobuf. This calls self.get_summary_proto() and calls the .Encode() method of the resulting object.'
def get_summary_proto_encoded(self):
return self.get_summary_proto().Encode()
'Return a protobuf representing a summary of this recorder.'
def get_summary_proto(self):
summary = datamodel_pb.RequestStatProto() summary.set_start_timestamp_milliseconds(int((self.start_timestamp * 1000))) method = self.http_method() if (method != 'GET'): summary.set_http_method(method) path = self.http_path() if (path != '/'): summary.set_http_path(path) query...
'Compute RPC statistics (how often each RPC endpoint is called). Returns: A dict mapping \'service.call\' keys to an array of objects giving call counts (int), call costs (int), and billed ops (dict from op to pb).'
def get_rpcstats(self):
rpcstats = {} with self._lock: values = [[trace.service_call_name(), trace.call_cost_microdollars(), trace.billed_ops_list()] for trace in self.traces] for value in values: if (value[0] in rpcstats): stats_for_rpc = rpcstats[value[0]] stats_for_rpc[0] += 1 ...
'Compute the total amount of API time for all RPCs. Deprecated. This value is no longer meaningful. Returns: An integer expressing megacycles.'
def get_total_api_mcycles(self):
warnings.warn('get_total_api_mcycles does not return a meaningful value', UserWarning, stacklevel=2) return 0
'Log the recorded data, for debugging. This logs messages using logging.info(). The amount of data logged is controlled by the level argument, which defaults to config.DUMP_LEVEL; if < 0 (the default) nothing is logged.'
def dump(self, level=None):
if (level is None): level = config.DUMP_LEVEL if (level < 0): return logging.info('APPSTATS: %s "%s %s%s" %s %.3f', format_time(self.start_timestamp), self.http_method(), self.http_path(), self.http_query(), self.http_status, (self.end_timestamp - self.start_timestamp)) fo...
'Extract the current call stack. The stack is limited to at most config.MAX_STACK frames; frames recognized by config.RE_STACK_SKIP are skipped; a frame recognized by config.RE_STACK_BOTTOM terminates the stack search. Args: trace: An IndividualRpcStatsProto instance that will be updated.'
def get_call_stack(self, trace):
frame = sys._getframe(0) while ((frame is not None) and (trace.call_stack_size() < config.MAX_STACK)): if (not self.get_frame_summary(frame, trace)): break frame = frame.f_back
'Initialize the class variable path_entries. The variable will hold a list of (i, entry) tuples where entry == sys.path[i], sorted from shortest to longest entry.'
@classmethod def init_sys_path_entries(cls):
cls.sys_path_entries = sorted(enumerate(sys.path), key=(lambda x: ((- len(x[1])), x[0])))
'Return a frame summary. Args: frame: A Python stack frame object. trace: An IndividualRpcStatsProto instance that will be updated. Returns: False if this stack frame matches config.RE_STACK_BOTTOM. True otherwise.'
def get_frame_summary(self, frame, trace):
if (self.sys_path_entries is None): self.init_sys_path_entries() filename = frame.f_code.co_filename if (filename and (not (filename.startswith('<') and filename.endswith('>')))): for (i, entry) in self.sys_path_entries: if filename.startswith(entry): filename = (...
'Return a string representing .start_timestamp_milliseconds().'
def start_time_formatted(self):
return format_time((self.start_timestamp_milliseconds() * 0.001))
'Return an int giving .api_mcycles() converted to milliseconds. Deprecated. This value is no longer meaningful. Returns: An integer expressing milliseconds.'
def api_milliseconds(self):
warnings.warn('api_milliseconds does not return a meaningful value', UserWarning, stacklevel=2) return 0
'Return an int giving .processor_mcycles() converted to milliseconds.'
def processor_milliseconds(self):
warnings.warn('processor_milliseconds does not return correct values', UserWarning, stacklevel=2) return mcycles_to_msecs(self._proto.processor_mcycles())
'Return the total number of RPCs across .rpc_stats_list().'
def combined_rpc_count(self):
if (self.__combined_rpc_count is None): self.__combined_rpc_count = sum((x.total_amount_of_calls() for x in self.rpc_stats_list())) return self.__combined_rpc_count
'Return the total cost of RPCs across .rpc_stats_list().'
def combined_rpc_cost_micropennies(self):
if (self.__combined_rpc_cost_micropennies is None): self.__combined_rpc_cost_micropennies = sum((x.total_cost_of_calls_microdollars() for x in self.rpc_stats_list())) return self.__combined_rpc_cost_micropennies
'Return the total billed ops for RPCs across .rpc_stats_list().'
def combined_rpc_billed_ops(self):
if (self.__combined_rpc_billed_ops is None): combined_ops_dict = {} for stats in self.rpc_stats_list(): _add_billed_ops_to_map(combined_ops_dict, stats.total_billed_ops_list()) self.__combined_rpc_billed_ops = billed_ops_to_str(combined_ops_dict.itervalues()) return self.__co...
'Called by Django before deciding which view to execute.'
def process_request(self, request):
start_recording()
'Called by Django just before returning a response.'
def process_response(self, request, response):
end_recording(response.status_code) return response
'Returns whether the current request has a recorder set.'
@_synchronized def has_recorder_for_current_request(self):
return (os.environ.get('REQUEST_ID_HASH') in self._recorders)
'Sets the recorder for the current request.'
@_synchronized def set_for_current_request(self, new_recorder):
self._recorders[os.environ.get('REQUEST_ID_HASH')] = new_recorder _set_global_recorder(new_recorder)
'Returns the recorder for the current request or None.'
@_synchronized def get_for_current_request(self):
return self._recorders.get(os.environ.get('REQUEST_ID_HASH'))
'Clears the recorder for the current request.'
@_synchronized def clear_for_current_request(self):
if (os.environ.get('REQUEST_ID_HASH') in self._recorders): del self._recorders[os.environ.get('REQUEST_ID_HASH')] _clear_global_recorder()
'Clears the recorders for all requests.'
@_synchronized def _clear_all(self):
self._recorders.clear() _clear_global_recorder()
'Convert to a list with values in the locations expected by the ui.'
def to_list(self):
return [self.name, self.calls, self.cost, self.billed_ops, self.cost_pct]
'Extract statistics from summaries.'
def _get_summary_data(self, summaries):
allstats = {} pathstats = {} pivot_path_rpc = {} pivot_rpc_path = {} total_cost_micropennies = 0 summaries = sorted(summaries, key=(lambda x: (- x.start_timestamp_milliseconds()))) for (index, summary) in enumerate(summaries): path_key = recording.config.extract_key(summary) ...
'Apply the filter to values extracted from an entity. Think of self.match_keys and self.match_values as representing a table with one row. For example: match_keys = (\'name\', \'age\', \'rank\') match_values = (\'Joe\', 24, 5) (Except that in reality, the values are represented by tuples produced by datastore_types.Pr...
def _apply(self, key_value_map):
columns = [] for key in self.match_keys: column = key_value_map.get(key) if (not column): return False columns.append(column) return (self.match_values in itertools.izip(*columns))
'Constructor. Args: key: The Parameter key, must be either an integer or a string.'
def __init__(self, key):
if (not isinstance(key, (int, long, basestring))): raise TypeError(('Parameter key must be an integer or string, not %s' % (key,))) self.__key = key
'Retrieve the key.'
@property def key(self):
return self.__key
'Helper to convert to datastore_query.Filter, or None.'
def _to_filter(self, post=False):
raise NotImplementedError
'Helper to extract post-filter Nodes, if any.'
def _post_filters(self):
return None
'Return a Node with Parameters replaced by the selected values. Args: bindings: A dict mapping integers and strings to values. used: A dict into which use of use of a binding is recorded. Returns: A Node instance.'
def resolve(self, bindings, used):
return self
'Constructor. Args: kind: Optional kind string. ancestor: Optional ancestor Key. filters: Optional Node representing a filter expression tree. orders: Optional datastore_query.Order object. app: Optional app id. namespace: Optional namespace. default_options: Optional QueryOptions object. projection: Optional list or t...
@utils.positional(1) def __init__(self, kind=None, ancestor=None, filters=None, orders=None, app=None, namespace=None, default_options=None, projection=None, group_by=None):
if (ancestor is not None): if isinstance(ancestor, ParameterizedThing): if isinstance(ancestor, ParameterizedFunction): if (ancestor.func != 'key'): raise TypeError('ancestor cannot be a GQL function other than KEY') else: ...
'Internal helper to fix the namespace. This is called to ensure that for queries without an explicit namespace, the namespace used by async calls is the one in effect at the time the async call is made, not the one in effect when the the request is actually generated.'
def _fix_namespace(self):
if (self.namespace is not None): return self namespace = namespace_manager.get_namespace() return self.__class__(kind=self.kind, ancestor=self.ancestor, filters=self.filters, orders=self.orders, app=self.app, namespace=namespace, default_options=self.default_options, projection=self.projection, grou...
'Run this query, putting entities into the given queue.'
@tasklets.tasklet def run_to_queue(self, queue, conn, options=None, dsquery=None):
try: multiquery = self._maybe_multi_query() if (multiquery is not None): (yield multiquery.run_to_queue(queue, conn, options=options)) return if (dsquery is None): dsquery = self._get_query(conn) rpc = dsquery.run_async(conn, options) while...
'Accessor for the kind (a string or None).'
@property def kind(self):
return self.__kind
'Accessor for the ancestor (a Key or None).'
@property def ancestor(self):
return self.__ancestor
'Accessor for the filters (a Node or None).'
@property def filters(self):
return self.__filters
'Accessor for the filters (a datastore_query.Order or None).'
@property def orders(self):
return self.__orders
'Accessor for the app (a string or None).'
@property def app(self):
return self.__app
'Accessor for the namespace (a string or None).'
@property def namespace(self):
return self.__namespace
'Accessor for the default_options (a QueryOptions instance or None).'
@property def default_options(self):
return self.__default_options
'Accessor for the group by properties (a tuple instance or None).'
@property def group_by(self):
return self.__group_by
'Accessor for the projected properties (a tuple instance or None).'
@property def projection(self):
return self.__projection
'True if results are guaranteed to contain a unique set of property values. This happens when every property in the group_by is also in the projection.'
@property def is_distinct(self):
return bool((self.__group_by and (set(self._to_property_names(self.__group_by)) <= set(self._to_property_names(self.__projection)))))
'Return a new Query with additional filter(s) applied.'
def filter(self, *args):
if (not args): return self preds = [] f = self.filters if f: preds.append(f) for arg in args: if (not isinstance(arg, Node)): raise TypeError(('Cannot filter a non-Node argument; received %r' % arg)) preds.append(arg) if (not preds): ...
'Return a new Query with additional sort order(s) applied.'
def order(self, *args):
if (not args): return self orders = [] o = self.orders if o: orders.append(o) for arg in args: if isinstance(arg, model.Property): orders.append(datastore_query.PropertyOrder(arg._name, _ASC)) elif isinstance(arg, datastore_query.Order): orders...
'Construct an iterator over the query. Args: **q_options: All query options keyword arguments are supported. Returns: A QueryIterator object.'
def iter(self, **q_options):
self.bind() return QueryIterator(self, **q_options)
'Map a callback function or tasklet over the query results. Args: callback: A function or tasklet to be applied to each result; see below. merge_future: Optional Future subclass; see below. **q_options: All query options keyword arguments are supported. Callback signature: The callback is normally called with an entity...
@utils.positional(2) def map(self, callback, pass_batch_into_callback=None, merge_future=None, **q_options):
return self.map_async(callback, pass_batch_into_callback=pass_batch_into_callback, merge_future=merge_future, **q_options).get_result()
'Map a callback function or tasklet over the query results. This is the asynchronous version of Query.map().'
@utils.positional(2) def map_async(self, callback, pass_batch_into_callback=None, merge_future=None, **q_options):
qry = self._fix_namespace() return tasklets.get_context().map_query(qry, callback, pass_batch_into_callback=pass_batch_into_callback, options=self._make_options(q_options), merge_future=merge_future)
'Fetch a list of query results, up to a limit. Args: limit: How many results to retrieve at most. **q_options: All query options keyword arguments are supported. Returns: A list of results.'
@utils.positional(2) def fetch(self, limit=None, **q_options):
return self.fetch_async(limit, **q_options).get_result()
'Fetch a list of query results, up to a limit. This is the asynchronous version of Query.fetch().'
@utils.positional(2) def fetch_async(self, limit=None, **q_options):
if (limit is None): default_options = self._make_options(q_options) if ((default_options is not None) and (default_options.limit is not None)): limit = default_options.limit else: limit = _MAX_LIMIT q_options['limit'] = limit q_options.setdefault('batch_size',...
'Get the first query result, if any. This is similar to calling q.fetch(1) and returning the first item of the list of results, if any, otherwise None. Args: **q_options: All query options keyword arguments are supported. Returns: A single result, or None if there are no results.'
def get(self, **q_options):
return self.get_async(**q_options).get_result()
'Get the first query result, if any. This is the asynchronous version of Query.get().'
def get_async(self, **q_options):
qry = self._fix_namespace() return qry._get_async(**q_options)
'Internal version of get_async().'
@tasklets.tasklet def _get_async(self, **q_options):
res = (yield self.fetch_async(1, **q_options)) if (not res): raise tasklets.Return(None) raise tasklets.Return(res[0])
'Count the number of query results, up to a limit. This returns the same result as len(q.fetch(limit)) but more efficiently. Note that you must pass a maximum value to limit the amount of work done by the query. Args: limit: How many results to count at most. **q_options: All query options keyword arguments are support...
@utils.positional(2) def count(self, limit=None, **q_options):
return self.count_async(limit, **q_options).get_result()
'Count the number of query results, up to a limit. This is the asynchronous version of Query.count().'
@utils.positional(2) def count_async(self, limit=None, **q_options):
qry = self._fix_namespace() return qry._count_async(limit=limit, **q_options)
'Internal version of count_async().'
@tasklets.tasklet def _count_async(self, limit=None, **q_options):
if ('offset' in q_options): raise NotImplementedError('.count() and .count_async() do not support offsets at present.') if ('limit' in q_options): raise TypeError('Cannot specify limit as a non-keyword argument and as a keyword argument ...
'Fetch a page of results. This is a specialized method for use by paging user interfaces. Args: page_size: The requested page size. At most this many results will be returned. In addition, any keyword argument supported by the QueryOptions class is supported. In particular, to fetch the next page, you pass the cursor...
@utils.positional(2) def fetch_page(self, page_size, **q_options):
return self.fetch_page_async(page_size, **q_options).get_result()
'Fetch a page of results. This is the asynchronous version of Query.fetch_page().'
@utils.positional(2) def fetch_page_async(self, page_size, **q_options):
qry = self._fix_namespace() return qry._fetch_page_async(page_size, **q_options)
'Internal version of fetch_page_async().'
@tasklets.tasklet def _fetch_page_async(self, page_size, **q_options):
q_options.setdefault('batch_size', page_size) q_options.setdefault('produce_cursors', True) it = self.iter(limit=(page_size + 1), **q_options) results = [] while (yield it.has_next_async()): results.append(it.next()) if (len(results) >= page_size): break try: ...
'Helper to construct a QueryOptions object from keyword arguments. Args: q_options: a dict of keyword arguments. Note that either \'options\' or \'config\' can be used to pass another QueryOptions object, but not both. If another QueryOptions object is given it provides default values. If self.default_options is set, ...
def _make_options(self, q_options):
if (not (q_options or self.__projection)): return self.default_options if ('options' in q_options): if ('config' in q_options): raise TypeError('You cannot use config= and options= at the same time') q_options['config'] = q_options.pop('options') ...
'Return a list giving the parameters required by a query.'
def analyze(self):
class MockBindings(dict, ): def __contains__(self, key): self[key] = None return True bindings = MockBindings() used = {} ancestor = self.ancestor if isinstance(ancestor, ParameterizedThing): ancestor = ancestor.resolve(bindings, used) filters = self.filte...
'Bind parameter values. Returns a new Query object.'
def bind(self, *args, **kwds):
return self._bind(args, kwds)
'Bind parameter values. Returns a new Query object.'
def _bind(self, args, kwds):
bindings = dict(kwds) for (i, arg) in enumerate(args): bindings[(i + 1)] = arg used = {} ancestor = self.ancestor if isinstance(ancestor, ParameterizedThing): ancestor = ancestor.resolve(bindings, used) filters = self.filters if (filters is not None): filters = filter...
'Constructor. Takes a Query and query options. This is normally called by Query.iter() or Query.__iter__().'
@utils.positional(2) def __init__(self, query, **q_options):
ctx = tasklets.get_context() options = query._make_options(q_options) callback = self._extended_callback self._iter = ctx.iter_query(query, callback=callback, pass_batch_into_callback=True, options=options) self._fut = None
'Return the cursor before the current item. You must pass a QueryOptions object with produce_cursors=True for this to work. If there is no cursor or no current item, raise BadArgumentError. Before next() has returned there is no cursor. Once the loop is exhausted, this returns the cursor after the last item.'
def cursor_before(self):
if (self._batch is None): raise datastore_errors.BadArgumentError('There is no cursor currently') return self._batch.cursor((self._index + self._exhausted))
'Return the cursor after the current item. You must pass a QueryOptions object with produce_cursors=True for this to work. If there is no cursor or no current item, raise BadArgumentError. Before next() has returned there is no cursor. Once the loop is exhausted, this returns the cursor after the last item.'
def cursor_after(self):
if (self._batch is None): raise datastore_errors.BadArgumentError('There is no cursor currently') return self._batch.cursor((self._index + 1))
'Return the list of indexes used for this query. This returns a list of index representations, where an index representation is the same as what is returned by get_indexes(). Before the first result, the information is unavailable, and then None is returned. This is not the same as an empty list -- the empty list mean...
def index_list(self):
return getattr(self._batch, 'index_list', None)
'Iterator protocol: get the iterator for this iterator, i.e. self.'
def __iter__(self):
return self
'Return whether a next item is (probably) available. This is not quite the same as has_next(), because when produce_cursors is set, some shortcuts are possible. However, in some cases (e.g. when the query has a post_filter) we can get a false positive (returns True but next() will raise StopIteration). There are no fa...
def probably_has_next(self):
if self._lookahead: return True if (self._batch is not None): return self._batch.more_results return self.has_next()
'Return whether a next item is available. See the module docstring for the usage pattern.'
def has_next(self):
return self.has_next_async().get_result()
'Return a Future whose result will say whether a next item is available. See the module docstring for the usage pattern.'
@tasklets.tasklet def has_next_async(self):
if (self._fut is None): self._fut = self._iter.getq() flag = True try: (yield self._fut) except EOFError: flag = False raise tasklets.Return(flag)
'Iterator protocol: get next item or raise StopIteration.'
def next(self):
if (self._fut is None): self._fut = self._iter.getq() try: ent = self._fut.get_result() self._consume_item() return ent except EOFError: self._exhausted = True raise StopIteration finally: self._fut = None
'Run this query, putting entities into the given queue.'
@tasklets.tasklet def run_to_queue(self, queue, conn, options=None):
if (options is None): offset = None limit = None keys_only = None else: offset = options.offset limit = options.limit keys_only = options.keys_only if (options.start_cursor or options.end_cursor or options.produce_cursors): names = set() ...
'Constructor. Args: enum_type: A subclass of protorpc.messages.Enum. name: Optional datastore name (defaults to the property name). Additional keywords arguments specify the same options as supported by IntegerProperty.'
@utils.positional((1 + _positional)) def __init__(self, enum_type, name=None, default=None, choices=None, **kwds):
self._enum_type = enum_type if (default is not None): self._validate(default) if (choices is not None): map(self._validate, choices) super(EnumProperty, self).__init__(name, default=default, choices=choices, **kwds)
'Validate an Enum value. Raises: TypeError if the value is not an instance of self._enum_type.'
def _validate(self, value):
if (not isinstance(value, self._enum_type)): raise TypeError(('Expected a %s instance, got %r instead' % (self._enum_type.__name__, value)))
'Convert an Enum value to a base type (integer) value.'
def _to_base_type(self, enum):
return enum.number