我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用google.appengine.ext.db.Key()。
def encode_xdb_key(key, encoder=None): """ Convert the `db.Key` to it's entity and encode it. """ gae_objects = getGAEObjects(encoder.context.extra) klass = db.class_for_kind(key.kind()) try: referenced_object = gae_objects.get(klass, key) except KeyError: referenced_object = db.get(key) gae_objects.set(klass, key, referenced_object) if not referenced_object: encoder.writeElement(None) else: encoder.writeObject(referenced_object)
def __get_value(self, name): """Get a BlobInfo value, loading entity if necessary. This method allows lazy loading of the underlying datastore entity. It should never be invoked directly. Args: name: Name of property to get value for. Returns: Value of BlobInfo property from entity. """ if self.__entity is None: self.__entity = datastore.Get( datastore_types.Key.from_path( self.kind(), str(self.__key), namespace='')) try: return self.__entity[name] except KeyError: raise AttributeError(name)
def show_product(request, product_key, template_name="store_product.html", form_class=ProductAddToCartForm): key = db.Key(product_key) query = Product.gql('WHERE __key__ = :1 AND is_active = True', key) product = query.get() if not product: raise Http404('Product not found!') page_title = product.name if request.method == 'POST': postdata = request.POST.copy() form = form_class(postdata) if form.is_valid(): cart.add(request, product_key) redirect_url = urlresolvers.reverse('show_cart') return HttpResponseRedirect(redirect_url) else: form = form_class() return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def shortKey(render, val): """ Jinja2 filter: Make a shortkey from an entity-key. :param val: Entity-key as string. :type val: str :returns: Shortkey on success, None on error. :rtype: str """ try: k = db.Key(encoded = unicode(val)) return k.id_or_name() except: return None
def _get_id(cls, obj): if cls._is_ndb(): if not isinstance(obj, ndb.Key): # Turn objects into keys key = obj.key else: key = obj obj_id = key.string_id() else: if not isinstance(obj, db.Key): # Turn objects into keys key = obj.key() else: key = obj obj_id = key.name() return obj_id
def _key_for_namespace(namespace, app): """Return the __namespace__ key for a namespace. Args: namespace: The namespace whose key is requested. app: The id of the application that the key belongs to. Returns: A db.Key representing the namespace. """ if namespace: return db.Key.from_path(metadata.Namespace.KIND_NAME, namespace, _app=app) else: return db.Key.from_path(metadata.Namespace.KIND_NAME, metadata.Namespace.EMPTY_NAMESPACE_ID, _app=app)
def encodeKey(self, key, encoding): """ Returns an AMF encoded representation of a L{db.Key} instance. @param key: The L{db.Key} to be encoded. @type key: L{db.Key} @param encoding: The AMF version. """ if hasattr(key, 'key'): # we have a db.Model instance try: key = key.key() except db.NotSavedError: key = None if not key: # the AMF representation of None if encoding == pyamf.AMF3: return '\x01' return '\x05' k = str(key) if encoding == pyamf.AMF3: return '\x06%s%s' % ( amf3.encode_int(len(k) << 1 | amf3.REFERENCE_BIT), k) return '\x02%s%s' % (struct.pack('>H', len(k)), k)
def test_encode_key(self): key = db.Key.from_path('PetModel', 'jessica') self.assertIsNone(db.get(key)) self.assertEncodes(key, ( '\x05' ), encoding=pyamf.AMF0 )
def decode_key(self, key): return db.Key(key)
def __normalize_and_convert_keys(cls, keys): """Normalize and convert all keys to BlobKey type. This method is based on datastore.NormalizeAndTypeCheck(). Args: keys: A single key or a list/tuple of keys. Keys may be a string or BlobKey Returns: Single key or list with all strings replaced by BlobKey instances. """ if isinstance(keys, (list, tuple)): multiple = True keys = list(keys) else: multiple = False keys = [keys] for index, key in enumerate(keys): if not isinstance(key, (basestring, BlobKey)): raise datastore_errors.BadArgumentError( 'Expected str or BlobKey; received %s (a %s)' % ( key, datastore.typename(key))) keys[index] = datastore.Key.from_path(cls.kind(), str(key), namespace='') if multiple: return keys else: return keys[0]
def advance(self, key): """Updates the start of the range immediately past the specified key. Args: key: A db.Key or ndb.Key. """ self.include_start = False if ndb is not None: if isinstance(key, ndb.Key): key = key.to_old_key() self.key_start = key
def __cmp__(self, other): """Compare two key ranges. Key ranges with a value of None for key_start or key_end, are always considered to have include_start=False or include_end=False, respectively, when comparing. Since None indicates an unbounded side of the range, the include specifier is meaningless. The ordering generated is total but somewhat arbitrary. Args: other: An object to compare to this one. Returns: -1: if this key range is less than other. 0: if this key range is equal to other. 1: if this key range is greater than other. """ if not isinstance(other, KeyRange): return 1 self_list = [self.key_start, self.key_end, self.direction, self.include_start, self.include_end, self._app, self.namespace] if not self.key_start: self_list[3] = False if not self.key_end: self_list[4] = False other_list = [other.key_start, other.key_end, other.direction, other.include_start, other.include_end, other._app, other.namespace] if not other.key_start: other_list[3] = False if not other.key_end: other_list[4] = False return cmp(self_list, other_list)
def update_item(item_key, quantity): key = db.Key(item_key) item = CartItem.get(key) if item: if quantity <= 0: item.delete() else: item.quantity = int(quantity) item.put()
def remove_item(item_key): key = db.Key(item_key) item = CartItem.get(key) if item: item.delete()
def show_category(request, category_key, template_name="store_category.html"): key = db.Key(category_key) query = Category.gql('WHERE __key__ = :1 AND is_active = True', key) category = query.get() if not category: raise Http404('Category not found!') products = category.products page_title = category.name return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def __init__(self, reference_class, *args, **kwargs): self._reference_class = reference_class super(KeyListProperty, self).__init__(db.Key, *args, **kwargs)
def trending(cls, start=None, limit=20): q = CrashReport.all() # only search for crashes that are not resolved q.filter('state IN ', ['unresolved', 'pending', 'submitted']) if start: q.filter('__key__ >', Key(start)) q.order('__key__') q.order('name') q.order('-count') uniques = set() trending = list() has_more = False for crash_report in q.run(): if len(uniques) > limit: has_more = True break else: if crash_report.name not in uniques: uniques.add(crash_report.name) crash_report = CrashReport.get_crash(crash_report.fingerprint) trending.append(CrashReport.to_json(crash_report)) trending = sorted(trending, key=lambda report: report['count'], reverse=True) return { 'trending': trending, 'has_more': has_more }
def handle(self): cursor = self.request.get("cursor") count = int(self.request.get("count", "50")) query = model.MapreduceState.all() if cursor: query.filter("__key__ >=", db.Key(cursor)) query.order("__key__") jobs_list = query.fetch(count + 1) if len(jobs_list) == (count + 1): self.json_response["cursor"] = str(jobs_list[-1].key()) jobs_list = jobs_list[:-1] all_jobs = [] for job in jobs_list: out = { "name": job.mapreduce_spec.name, "mapreduce_id": job.mapreduce_spec.mapreduce_id, "active": job.active, "start_timestamp_ms": int(time.mktime(job.start_time.utctimetuple()) * 1000), "updated_timestamp_ms": int(time.mktime(job.last_poll_time.utctimetuple()) * 1000), "chart_url": job.sparkline_url, "chart_width": job.chart_width, "active_shards": job.active_shards, "shards": job.mapreduce_spec.mapper.shard_count, } if job.result_status: out["result_status"] = job.result_status all_jobs.append(out) self.json_response["jobs"] = all_jobs
def _iter_key_range(self, k_range): """Yields a db.Key and the value that should be yielded by self.__iter__(). Args: k_range: The key_range.KeyRange to iterate over. Yields: A 2-tuple containing the last db.Key processed and the value that should be yielded by __iter__. The returned db.Key will be used to determine the InputReader's current position in self._current_key_range. """ raise NotImplementedError("_iter_key_range() not implemented in %s" % self.__class__)
def __init__(self, key_start=None, key_end=None, direction=None, include_start=True, include_end=True, namespace=None, _app=None): """Initialize a KeyRange object. Args: key_start: The starting key for this range (db.Key or ndb.Key). key_end: The ending key for this range (db.Key or ndb.Key). direction: The direction of the query for this range. include_start: Whether the start key should be included in the range. include_end: Whether the end key should be included in the range. namespace: The namespace for this range. If None then the current namespace is used. NOTE: If NDB keys are passed in, they are converted to db.Key instances before being stored. """ if direction is None: direction = KeyRange.ASC assert direction in (KeyRange.ASC, KeyRange.DESC) self.direction = direction if ndb is not None: if isinstance(key_start, ndb.Key): key_start = key_start.to_old_key() if isinstance(key_end, ndb.Key): key_end = key_end.to_old_key() self.key_start = key_start self.key_end = key_end self.include_start = include_start self.include_end = include_end if namespace is not None: self.namespace = namespace else: self.namespace = namespace_manager.get_namespace() self._app = _app