desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Implementation of channel.send_message. Queues a message to be retrieved by the client when it polls. Args: request: A SendMessageRequest. response: A VoidProto.'
def _Dynamic_SendChannelMessage(self, request, response):
application_key = urllib.quote(request.application_key()) if (not request.message()): raise apiproxy_errors.ApplicationError(channel_service_pb.ChannelServiceError.BAD_MESSAGE) appname = os.environ['APPNAME'] unique_app_id = hashlib.sha1((appname + application_key)).hexdigest() jid = ('chann...
'Returns the app key from a given client id. Args: client_id: String representing a client id, returned by CreateChannel. Returns: String representing the application key used to create this client_id, or None if this client_id is incorrectly formed and doesn\'t map to an application key.'
def app_key_from_client_id(self, client_id):
pieces = client_id.split('-', 2) if (len(pieces) == 3): atindex = pieces[2].rfind('@') token = pieces[2] appkey = token[0:atindex] return appkey else: return None
'Constructor. Creates a Key from a string. Args: # a base64-encoded primary key, generated by Key.__str__ encoded: str'
def __init__(self, encoded=None):
self._str = None if (encoded is not None): if (not isinstance(encoded, basestring)): try: repr_encoded = repr(encoded) except: repr_encoded = "<couldn't encode>" raise datastore_errors.BadArgumentError(('Key() expects a stri...
'Construct the "path" of this key as a list. Returns: A list [kind_1, id_or_name_1, ..., kind_n, id_or_name_n] of the key path. Raises: datastore_errors.BadKeyError if this key does not have a valid path.'
def to_path(self, _default_id=None, _decode=True, _fail=True):
def Decode(s): if _decode: try: return s.decode('utf-8') except UnicodeDecodeError: if _fail: raise return s path = [] for path_element in self.__reference.path().element_list(): path.append(Decode(path_eleme...
'Static method to construct a Key out of a "path" (kind, id or name, ...). This is useful when an application wants to use just the id or name portion of a key in e.g. a URL, where the rest of the URL provides enough context to fill in the rest, i.e. the app id (always implicit), the entity kind, and possibly an ancest...
@staticmethod def from_path(*args, **kwds):
parent = kwds.pop('parent', None) app_id = ResolveAppId(kwds.pop('_app', None)) namespace = kwds.pop('namespace', None) if kwds: raise datastore_errors.BadArgumentError(('Excess keyword arguments ' + repr(kwds))) if ((not args) or (len(args) % 2)): raise datastore_errors.Bad...
'Returns this entity\'s app id, a string.'
def app(self):
if self.__reference.app(): return self.__reference.app().decode('utf-8') else: return None
'Returns this entity\'s namespace, a string.'
def namespace(self):
if self.__reference.has_name_space(): return self.__reference.name_space().decode('utf-8') else: return ''
'Returns this entity\'s kind, as a string.'
def kind(self):
if (self.__reference.path().element_size() > 0): encoded = self.__reference.path().element_list()[(-1)].type() return unicode(encoded.decode('utf-8')) else: return None
'Returns this entity\'s id, or None if it doesn\'t have one.'
def id(self):
elems = self.__reference.path().element_list() if (elems and elems[(-1)].has_id() and elems[(-1)].id()): return elems[(-1)].id() else: return None
'Returns this entity\'s name, or None if it doesn\'t have one.'
def name(self):
elems = self.__reference.path().element_list() if (elems and elems[(-1)].has_name() and elems[(-1)].name()): return elems[(-1)].name().decode('utf-8') else: return None
'Returns this entity\'s id or name, whichever it has, or None.'
def id_or_name(self):
if (self.id() is not None): return self.id() else: return self.name()
'Returns True if this entity has an id or name, False otherwise.'
def has_id_or_name(self):
elems = self.__reference.path().element_list() if elems: e = elems[(-1)] return bool((e.name() or e.id())) else: return False
'Returns this entity\'s parent, as a Key. If this entity has no parent, returns None.'
def parent(self):
if (self.__reference.path().element_size() > 1): parent = Key() parent.__reference.CopyFrom(self.__reference) del parent.__reference.path().element_list()[(-1)] return parent else: return None
'Returns a tag: URI for this entity for use in XML output. Foreign keys for entities may be represented in XML output as tag URIs. RFC 4151 describes the tag URI scheme. From http://taguri.org/: The tag algorithm lets people mint - create - identifiers that no one else using the same algorithm could ever mint. It is si...
def ToTagUri(self):
if (not self.has_id_or_name()): raise datastore_errors.BadKeyError('ToTagUri() called for an entity with an incomplete key.') return (u'tag:%s.%s,%s:%s[%s]' % (saxutils.escape(EncodeAppIdNamespace(self.app(), self.namespace())), os.environ['AUTH_DOMAIN'], datetime.date.today().is...
'Returns this key\'s entity group as a Key. Note that the returned Key will be incomplete if this Key is for a root entity and it is incomplete.'
def entity_group(self):
group = Key._FromPb(self.__reference) del group.__reference.path().element_list()[1:] return group
'Static factory method. Creates a Key from an entity_pb.Reference. Not intended to be used by application developers. Enforced by hiding the entity_pb classes. Args: pb: entity_pb.Reference'
@staticmethod def _FromPb(pb):
if (not isinstance(pb, entity_pb.Reference)): raise datastore_errors.BadArgumentError(('Key constructor takes an entity_pb.Reference; received %s (a %s).' % (pb, typename(pb)))) key = Key() key.__reference = entity_pb.Reference() key.__reference.CopyFrom(pb) return ke...
'Converts this Key to its protocol buffer representation. Not intended to be used by application developers. Enforced by hiding the entity_pb classes. Returns: # the Reference PB representation of this Key entity_pb.Reference'
def _ToPb(self):
pb = entity_pb.Reference() pb.CopyFrom(self.__reference) if (not self.has_id_or_name()): pb.mutable_path().element_list()[(-1)].set_id(0) pb.app().decode('utf-8') for pathelem in pb.path().element_list(): pathelem.type().decode('utf-8') return pb
'Encodes this Key as an opaque string. Returns a string representation of this key, suitable for use in HTML, URLs, and other similar use cases. If the entity\'s key is incomplete, raises a BadKeyError. Unfortunately, this string encoding isn\'t particularly compact, and its length varies with the length of the path. I...
def __str__(self):
try: if (self._str is not None): return self._str except AttributeError: pass if self.has_id_or_name(): encoded = base64.urlsafe_b64encode(self.__reference.Encode()) self._str = encoded.replace('=', '') else: raise datastore_errors.BadKeyError(('Cannot...
'Returns an eval()able string representation of this key. Returns a Python string of the form \'datastore_types.Key.from_path(...)\' that can be used to recreate this key. Returns: string'
def __repr__(self):
args = [] for elem in self.__reference.path().element_list(): args.append(repr(elem.type().decode('utf-8'))) if elem.has_name(): args.append(repr(elem.name().decode('utf-8'))) else: args.append(repr(elem.id())) args.append(('_app=%r' % self.__reference.app().d...
'Returns negative, zero, or positive when comparing two keys. TODO: for API v2, we should change this to make incomplete keys, ie keys without an id or name, not equal to any other keys. Args: other: Key to compare to. Returns: Negative if self is less than "other" Zero if "other" is equal to self Positive if self is g...
def __cmp__(self, other):
if (not isinstance(other, Key)): return (-2) self_args = [self.__reference.app(), self.__reference.name_space()] self_args += self.to_path(_default_id=0, _decode=False) other_args = [other.__reference.app(), other.__reference.name_space()] other_args += other.to_path(_default_id=0, _decode=F...
'Returns an integer hash of this key. Implements Python\'s hash protocol so that Keys may be used in sets and as dictionary keys. Returns: int'
def __hash__(self):
args = self.to_path(_default_id=0, _fail=False) args.append(self.__reference.app()) return (hash(type(args)) ^ hash(tuple(args)))
'Returns an integer hash of this point. Implements Python\'s hash protocol so that GeoPts may be used in sets and as dictionary keys. Returns: int'
def __hash__(self):
return hash((self.lat, self.lon))
'Returns an eval()able string representation of this GeoPt. The returned string is of the form \'datastore_types.GeoPt([lat], [lon])\'. Returns: string'
def __repr__(self):
return ('datastore_types.GeoPt(%r, %r)' % (self.lat, self.lon))
'Returns an eval()able string representation of this IM. The returned string is of the form: datastore_types.IM(\'address\', \'protocol\') Returns: string'
def __repr__(self):
return ('datastore_types.IM(%r, %r)' % (self.protocol, self.address))
'Constructor. We only accept unicode and str instances, the latter with encoding. Args: arg: optional unicode or str instance; default u\'\' encoding: optional encoding; disallowed when isinstance(arg, unicode), defaults to \'ascii\' when isinstance(arg, str);'
def __new__(cls, arg=None, encoding=None):
if (arg is None): arg = u'' if isinstance(arg, unicode): if (encoding is not None): raise TypeError('Text() with a unicode argument should not specify an encoding') return super(Text, cls).__new__(cls, arg) if isinstance(arg, str): if (e...
'Constructor. We only accept str instances. Args: arg: optional str instance (default \'\')'
def __new__(cls, arg=None):
if (arg is None): arg = '' if isinstance(arg, str): return super(_BaseByteType, cls).__new__(cls, arg) raise TypeError(('%s() argument should be str instance, not %s' % (cls.__name__, type(arg).__name__)))
'Output bytes as XML. Returns: Base64 encoded version of itself for safe insertion in to an XML document.'
def ToXml(self):
encoded = base64.urlsafe_b64encode(self) return saxutils.escape(encoded)
'Constructor. Args: arg: optional str or EntityProto instance (default \'\')'
def __new__(cls, arg=None):
if isinstance(arg, entity_pb.EntityProto): arg = arg.SerializePartialToString() return super(EmbeddedEntity, cls).__new__(cls, arg)
'Constructor. Used to convert a string to a BlobKey. Normally used internally by Blobstore API. Args: blob_key: Key name of BlobReference that this key belongs to.'
def __init__(self, blob_key):
ValidateString(blob_key, 'blob-key') self.__blob_key = blob_key
'Convert to string.'
def __str__(self):
return self.__blob_key
'Returns an eval()able string representation of this key. Returns a Python string of the form \'datastore_types.BlobKey(...)\' that can be used to recreate this key. Returns: string'
def __repr__(self):
return ('datastore_types.%s(%r)' % (type(self).__name__, self.__blob_key))
'Emit a record. This implementation is based on the implementation of StreamHandler.emit().'
def emit(self, record):
try: message = self._AppLogsMessage(record) if isinstance(message, unicode): message = message.encode('UTF-8') logservice.write(message) except (KeyboardInterrupt, SystemExit, runtime.DeadlineExceededError): raise except: pass
'Converts the log record into a log line.'
def _AppLogsMessage(self, record):
message = self.format(record).replace('\r\n', NEWLINE_REPLACEMENT) message = message.replace('\r', NEWLINE_REPLACEMENT) message = message.replace('\n', NEWLINE_REPLACEMENT) return ('LOG %d %d %s\n' % (self._AppLogsLevel(record.levelno), long(((record.created * 1000) * 1000)), message))
'Converts the logging level used in Python to the API logging level'
def _AppLogsLevel(self, level):
if (level >= logging.CRITICAL): return 4 elif (level >= logging.ERROR): return 3 elif (level >= logging.WARNING): return 2 elif (level >= logging.INFO): return 1 else: return 0
'Validates a subnet.'
def Validate(self, value, unused_key=None):
if (value is None): raise validation.MissingAttribute('subnet must be specified') if (not isinstance(value, basestring)): raise validation.ValidationError(("subnet must be a string, not '%r'" % type(value))) try: ipaddr.IPNetwork(value) except ValueErro...
'Constructor. Args: service_name: Service name expected for all calls. app_id: The application identifier.'
def __init__(self, service_name='search', app_id=''):
super(SearchServiceStub, self).__init__(service_name) try: with open(_SEARCH_LOCATION_FILE) as location_file: search_ip = (location_file.read().strip() or None) except IOError: search_ip = None if (search_ip is not None): self.__search_location = '{}:{}'.format(search...
'A local implementation of SearchService.IndexDocument RPC. Index a new document or update an existing document. Args: request: A search_service_pb.IndexDocumentRequest. response: A search_service_pb.IndexDocumentResponse.'
def _Dynamic_IndexDocument(self, request, response):
if (not request.has_app_id()): request.set_app_id(self.__app_id) self._RemoteSend(request, response, 'IndexDocument')
'A local implementation of SearchService.DeleteDocument RPC. Args: request: A search_service_pb.DeleteDocumentRequest. response: A search_service_pb.DeleteDocumentResponse.'
def _Dynamic_DeleteDocument(self, request, response):
self._RemoteSend(request, response, 'DeleteDocument')
'A local implementation of SearchService.ListIndexes RPC. Args: request: A search_service_pb.ListIndexesRequest. response: A search_service_pb.ListIndexesResponse. Raises: ResponseTooLargeError: raised for testing admin console.'
def _Dynamic_ListIndexes(self, request, response):
self._RemoteSend(request, response, 'ListIndexes')
'A local implementation of SearchService.ListDocuments RPC. Args: request: A search_service_pb.ListDocumentsRequest. response: A search_service_pb.ListDocumentsResponse.'
def _Dynamic_ListDocuments(self, request, response):
self._RemoteSend(request, response, 'ListDocuments')
'A local implementation of SearchService.Search RPC. Args: request: A search_service_pb.SearchRequest. response: A search_service_pb.SearchResponse.'
def _Dynamic_Search(self, request, response):
if (not request.has_app_id()): request.set_app_id(self.__app_id) self._RemoteSend(request, response, 'Search')
'Write search indexes to the index file. This method is a no-op.'
def Write(self):
return
'Read search indexes from the index file. This method is a no-op if index_file is set to None.'
def Read(self):
return
'Sends a request remotely to the datstore server. Args: request: A request object. response: A response object to be filled in. method: A str, the dynamic function doing the call.'
def _RemoteSend(self, request, response, method):
if (not self.__search_location): raise search.InternalError('Search service not configured.') api_request = remote_api_pb.Request() api_request.set_method(method) api_request.set_service_name('search') api_request.set_request(request.Encode()) api_response = remote_api_pb.Respon...
'Initializer. Args: doc_id: The identifier of the document with token occurrences. Raises: TypeError: If an unknown argument is passed.'
def __init__(self, doc_id):
self._doc_id = doc_id self._positions = []
'Return id of the document that the token occurred in.'
@property def doc_id(self):
return self._doc_id
'Adds the position in token sequence to occurrences for token.'
def AddPosition(self, position):
pos = bisect.bisect_left(self._positions, position) if ((pos < len(self._positions)) and (self._positions[pos] == position)): return self._positions.insert(pos, position)
'Removes the position in token sequence from occurrences for token.'
def RemovePosition(self, position):
pos = bisect.bisect_left(self._positions, position) if ((pos < len(self._positions)) and (self._positions[pos] == position)): del self._positions[pos]
'Adds the token position for the given doc_id.'
def Add(self, doc_id, position):
posting = Posting(doc_id=doc_id) pos = bisect.bisect_left(self._postings, posting) if ((pos < len(self._postings)) and (self._postings[pos].doc_id == posting.doc_id)): posting = self._postings[pos] else: self._postings.insert(pos, posting) posting.AddPosition(position)
'Removes the token position for the given doc_id.'
def Remove(self, doc_id, position):
posting = Posting(doc_id=doc_id) pos = bisect.bisect_left(self._postings, posting) if ((pos < len(self._postings)) and (self._postings[pos].doc_id == posting.doc_id)): posting = self._postings[pos] posting.RemovePosition(position) if (not posting.positions): del self._pos...
'Adds an occurrence of the term to the stats for the document.'
def IncrementTermCount(self, term):
count = 0 if (term in self._term_stats): count = self._term_stats[term] count += 1 self._term_stats[term] = count
'Returns the term frequency in the document.'
def TermFrequency(self, term):
if (term not in self._term_stats): return 0 return self._term_stats[term]
'Returns the collection of term frequencies in the document.'
@property def term_stats(self):
return self._term_stats
'Adds the doc_id to set in index.'
def _AddDocumentId(self, doc_id):
self._document_ids.add(doc_id)
'Removes the doc_id from the set in index.'
def _RemoveDocumentId(self, doc_id):
if (doc_id in self._document_ids): self._document_ids.remove(doc_id)
'Adds the type to the list supported for a named field.'
def _AddFieldType(self, name, field_type):
if (name not in self._schema): field_types = document_pb.FieldTypes() field_types.set_name(name) self._schema[name] = field_types field_types = self._schema[name] if (field_type not in field_types.type_list()): field_types.add_type(field_type)
'Gets statistics about occurrences of terms in document.'
def GetDocumentStats(self, document):
document_stats = _DocumentStatistics() for field in document.field_list(): for token in self._tokenizer.TokenizeValue(field_value=field.value()): document_stats.IncrementTermCount(token.chars) return document_stats
'Adds a document into the index.'
def AddDocument(self, doc_id, document):
token_position = 0 for field in document.field_list(): self._AddFieldType(field.name(), field.value().type()) self._AddTokens(doc_id, field.name(), field.value(), token_position) self._AddDocumentId(doc_id)
'Removes a document from the index.'
def RemoveDocument(self, document):
doc_id = document.id() for field in document.field_list(): self._RemoveTokens(doc_id, field.name(), field.value()) self._RemoveDocumentId(doc_id)
'Adds token occurrences for a given doc\'s field value.'
def _AddTokens(self, doc_id, field_name, field_value, token_position):
for token in self._tokenizer.TokenizeValue(field_value, token_position): self._AddToken(doc_id, token) self._AddToken(doc_id, token.RestrictField(field_name))
'Removes tokens occurrences for a given doc\'s field value.'
def _RemoveTokens(self, doc_id, field_name, field_value):
for token in self._tokenizer.TokenizeValue(field_value=field_value): self._RemoveToken(doc_id, token) self._RemoveToken(doc_id, token.RestrictField(field_name))
'Adds a token occurrence for a document.'
def _AddToken(self, doc_id, token):
postings = self._inverted_index.get(token) if (postings is None): self._inverted_index[token] = postings = PostingList() postings.Add(doc_id, token.position)
'Removes a token occurrence for a document.'
def _RemoveToken(self, doc_id, token):
if (token in self._inverted_index): postings = self._inverted_index[token] postings.Remove(doc_id, token.position) if (not postings.postings): del self._inverted_index[token]
'Returns all document postings which for the token.'
def GetPostingsForToken(self, token):
if (token in self._inverted_index): return self._inverted_index[token].postings return []
'Returns the schema for the index.'
def GetSchema(self):
return self._schema
'Returns the index specification for the index.'
@property def index_spec(self):
return self._index_spec
'Indexes an iterable DocumentPb.Document.'
def IndexDocuments(self, documents, response):
for document in documents: doc_id = document.id() if (not doc_id): doc_id = str(uuid.uuid4()) document.set_id(doc_id) response.add_doc_id(doc_id) if (doc_id in self._documents): old_document = self._documents[doc_id] self._inverted_inde...
'Deletes documents for the given document_ids.'
def DeleteDocuments(self, document_ids, response):
for document_id in document_ids: if (document_id in self._documents): document = self._documents[document_id] self._inverted_index.RemoveDocument(document) del self._documents[document_id] delete_status = response.add_status() delete_status.set_code(search...
'Returns the documents in the index.'
def Documents(self):
return self._documents.values()
'Return the term frequency in the document.'
def _TermFrequency(self, term, document):
return self._inverted_index.GetDocumentStats(document).TermFrequency(term)
'Returns the count of documents in the index.'
@property def document_count(self):
return self._inverted_index.document_count
'Returns the document count for documents containing the term.'
def _DocumentCountForTerm(self, term):
return len(self._PostingsForToken(tokens.Token(chars=term)))
'Returns inverse document frequency of term.'
def _InverseDocumentFrequency(self, term):
doc_count = self._DocumentCountForTerm(term) if doc_count: return math.log10((self.document_count / float(doc_count))) else: return 0
'Returns the term frequency times inverse document frequency of term.'
def _TermFrequencyInverseDocumentFrequency(self, term, document):
return (self._TermFrequency(term, document) * self._InverseDocumentFrequency(term))
'Scores a document for the given query.'
def _ScoreDocument(self, document, score, terms):
if (not score): return 0 tf_idf = 0 for term in terms: tf_idf += self._TermFrequencyInverseDocumentFrequency(term, document) return tf_idf
'Returns the postings for the token.'
def _PostingsForToken(self, token):
return self._inverted_index.GetPostingsForToken(token)
'Get all search terms for scoring.'
def _CollectTerms(self, node):
if (node.getType() in search_util.TEXT_QUERY_TYPES): return set([query_parser.GetQueryNodeText(node).strip('"')]) elif node.children: if ((node.getType() == QueryParser.EQ) and (len(node.children) > 1)): children = node.children[1:] else: children = node.children ...
'Retrieve scored results for a search query.'
def _Evaluate(self, node, score=True):
doc_match = document_matcher.DocumentMatcher(node, self._inverted_index) matched_documents = doc_match.FilterDocuments(self._documents.itervalues()) terms = self._CollectTerms(node) scored_documents = [_ScoredDocument(doc, self._ScoreDocument(doc, score, terms)) for doc in matched_documents] return ...
'Searches the simple index for .'
def Search(self, search_request):
query = urllib.unquote(search_request.query()) query = query.strip() score = _ScoreRequested(search_request) if (not query): docs = [_ScoredDocument(doc, 0.0) for doc in self._documents.values()] else: if (not isinstance(query, unicode)): query = unicode(query, 'utf-8') ...
'Returns the schema for the index.'
def GetSchema(self):
return self._inverted_index.GetSchema()
'Constructor. Args: service_name: Service name expected for all calls. index_file: The file to which search indexes will be persisted.'
def __init__(self, service_name='search', index_file=None):
self.__indexes = {} self.__index_file = index_file self.__index_file_lock = threading.Lock() super(SearchServiceStub, self).__init__(service_name) self.Read()
'Get namespace name. Args: namespace: Namespace provided in request arguments. Returns: If namespace is None, returns the name of the current global namespace. If namespace is not None, returns namespace.'
def _GetNamespace(self, namespace):
if (namespace is not None): return namespace return namespace_manager.get_namespace()
'A local implementation of SearchService.IndexDocument RPC. Index a new document or update an existing document. Args: request: A search_service_pb.IndexDocumentRequest. response: An search_service_pb.IndexDocumentResponse.'
def _Dynamic_IndexDocument(self, request, response):
params = request.params() index = self._GetIndex(params.index_spec(), create=True) index.IndexDocuments(params.document_list(), response)
'A local implementation of SearchService.DeleteDocument RPC. Args: request: A search_service_pb.DeleteDocumentRequest. response: An search_service_pb.DeleteDocumentResponse.'
def _Dynamic_DeleteDocument(self, request, response):
params = request.params() index_spec = params.index_spec() index = self._GetIndex(index_spec) if (index is None): self._UnknownIndex(response.add_status(), index_spec) return index.DeleteDocuments(params.doc_id_list(), response)
'A local implementation of SearchService.ListIndexes RPC. Args: request: A search_service_pb.ListIndexesRequest. response: An search_service_pb.ListIndexesResponse. Raises: ResponseTooLargeError: raised for testing admin console.'
def _Dynamic_ListIndexes(self, request, response):
if request.has_app_id(): if random.choice(([True] + ([False] * 9))): raise apiproxy_errors.ResponseTooLargeError() for _ in xrange((random.randint(0, 2) * random.randint(5, 15))): new_index_spec = response.add_index_metadata().mutable_index_spec() new_index_spec.s...
'A local implementation of SearchService.ListDocuments RPC. Args: request: A search_service_pb.ListDocumentsRequest. response: An search_service_pb.ListDocumentsResponse.'
def _Dynamic_ListDocuments(self, request, response):
params = request.params() index = self._GetIndex(params.index_spec(), create=True) if (index is None): self._UnknownIndex(response.mutable_status(), params.index_spec()) return num_docs = 0 start = (not params.has_start_doc_id()) for document in sorted(index.Documents(), key=(lam...
'Fills the SearchResponse with the first set of results.'
def _DefaultFillSearchResponse(self, params, results, response):
position_range = range(0, min(params.limit(), len(results))) self._FillSearchResponse(results, position_range, params.cursor_type(), _ScoreRequested(params), response)
'Copies Document, doc, to doc_copy restricting fields to field_spec.'
def _CopyDocument(self, doc, doc_copy, field_spec=None, ids_only=None):
if ids_only: self._CopyBaseDocument(doc, doc_copy) elif (field_spec and field_spec.name_list()): self._CopyBaseDocument(doc, doc_copy) for field in doc.field_list(): if (field.name() in field_spec.name_list()): doc_copy.add_field().CopyFrom(field) else: ...
'Fills the SearchResponse with a selection of results.'
def _FillSearchResponse(self, results, position_range, cursor_type, score, response, field_spec=None, ids_only=None):
for i in position_range: result = results[i] search_result = response.add_result() self._CopyDocument(result.document, search_result.mutable_document(), field_spec, ids_only) if (cursor_type == search_service_pb.SearchParams.PER_RESULT): search_result.set_cursor(result.do...
'A local implementation of SearchService.Search RPC. Args: request: A search_service_pb.SearchRequest. response: An search_service_pb.SearchResponse.'
def _Dynamic_Search(self, request, response):
if request.has_app_id(): self._RandomSearchResponse(request, response) return index = None index = self._GetIndex(request.params().index_spec()) if (index is None): self._UnknownIndex(response.mutable_status(), request.params().index_spec()) response.set_matched_count(0) ...
'Write search indexes to the index file. This method is a no-op if index_file is set to None.'
def Write(self):
if (not self.__index_file): return (descriptor, tmp_filename) = tempfile.mkstemp(dir=os.path.dirname(self.__index_file)) tmpfile = os.fdopen(descriptor, 'wb') pickler = pickle.Pickler(tmpfile, protocol=1) pickler.fast = True pickler.dump((self._VERSION, self.__indexes)) tmpfile.close...
'Read search indexes from the index file. This method is a no-op if index_file is set to None.'
def Read(self):
if (not self.__index_file): return read_indexes = self._ReadFromFile() if read_indexes: self.__indexes = read_indexes
'Initializer. Args: code: The error or success code of the operation. message: An error message associated with any error. id: The id of the object some operation was performed on. Raises: TypeError: If an unknown attribute is passed. ValueError: If an unknown code is passed.'
def __init__(self, code, message=None, id=None):
self._message = _ConvertToUnicode(message) self._code = code if (self._code not in self._CODES): raise ValueError(('Unknown operation result code %r, must be one of %s' % (self._code, self._CODES))) self._id = _ConvertToUnicode(id)
'Returns the code indicating the status of the operation.'
@property def code(self):
return self._code
'Returns any associated error message if the operation was in error.'
@property def message(self):
return self._message
'Returns the Id of the object the operation was performed on.'
@property def id(self):
return self._id
'Initializer. Args: message: A message detailing the cause of the failure to index some document. results: A list of PutResult corresponding to the list of objects requested to be indexed.'
def __init__(self, message, results):
super(PutError, self).__init__(message) self._results = results
'Returns PutResult list corresponding to objects indexed.'
@property def results(self):
return self._results
'Initializer. Args: message: A message detailing the cause of the failure to delete some document. results: A list of DeleteResult corresponding to the list of Ids of objects requested to be deleted.'
def __init__(self, message, results):
super(DeleteError, self).__init__(message) self._results = results
'Returns DeleteResult list corresponding to Documents deleted.'
@property def results(self):
return self._results