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)
python类Key()的实例源码
_google_appengine_ext_db.py 文件源码
项目:Tinychat-Bot--Discontinued
作者: Tinychat
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
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 __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 __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 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 __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 _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 __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 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
)
_google_appengine_ext_db.py 文件源码
项目:Tinychat-Bot--Discontinued
作者: Tinychat
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
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 __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 __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 __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)