NDB Context 类

应用可以使用 Context 来控制其缓存政策。 Context 还为集成到 NDB 异步设施的 Memcache 和网址提取提供了方便的异步 API;具体来说,Memcache API 支持自动批处理功能。

缓存管理实例方法

clear_cache()
清除上下文缓存。
flush()
清空所有自动批处理程序队列(将队列的工作发送到服务器)。 清空操作会异步执行。

返回 Future。要等待清空完成,请调用此对象的 wait() 方法。

get_cache_policy()
返回缓存政策函数。 此政策函数采用 Key 实例参数,并返回 bool 来指示是否应该在上下文缓存中缓存具有此键的实体。可能是 None(表示使用 default_cache_policy)。
get_datastore_policy()
返回当前上下文 Datastore 政策函数。 此政策函数采用 Key 实例参数并返回bool来指示其是否应使用 Datastore。可能是 None(表示使用 default_datastore_policy)。
get_memcache_policy()
返回当前的 Memcache 政策函数。 此政策函数采用 Key 实例参数并返回 bool 来指示是否应对其进行缓存。可能是 None(表示使用 default_memcache_policy)。
get_memcache_timeout_policy()
返回当前的 Memcache 超时政策函数。 此政策函数采用 Key 实例参数,并返回需要的 Memcache 超时值(以秒为单位)或者返回零以使用默认超时值。可能是 None,其使用 default_memcache_timeout_policy
set_cache_policy(func)
设置缓存政策函数。

参数

func
此政策函数采用 Key 实例参数,并返回 bool 来指示具有此键的实体是否应缓存在上下文缓存中。可能是 None
set_datastore_policy(func)
设置 Datastore 政策函数。

参数

func
此政策函数采用 Key 实例参数,并返回 bool 来指示具有此键的实体是否应存储在永久性 Datastore 中。可能是 None
set_memcache_policy(func)
设置 Memcache 政策函数。

参数

func
此政策函数采用 Key 实例参数,并返回 bool 来指示具有此键的实体是否应缓存在上下文缓存中。可能是 None
set_memcache_timeout_policy(func)
设置 Memcache 超时政策函数。

参数

func
此政策函数采用 Key 实例参数,并返回所需的 Memcache 超时值(以秒为单位),或者返回零以使用默认超时值。可能是 None

Memcache 和 Urlfetch 实例方法

如需完整的方法列表,请参阅 Memcache API 参考。以下列表清楚地展示了一些更常用的方法:

memcache_add(key, value, time, namespace)
异步自动批处理 memcache add()
memcache_cas(key, value, time, namespace)
异步自动批处理 memcache Client cas()(比较和交换)。
memcache_decr(key, delta, initial_value, namespace)
异步自动批处理 memcache decr()
memcache_delete(key, seconds, namespace)
异步自动批处理 memcache delete()
memcache_get(key, namespace, use_cache)
异步自动批处理 memcache get()

返回 Future,其返回值是从 memcache 中检索到的值或None

memcache_gets(key, namespace, use_cache)
异步自动批处理 memcache gets()
memcache_incr(key, delta, initial_value, namespace)
异步自动批处理 memcache incr()
memcache_replace(key, value, time, namespace)
异步自动批处理 memcache replace()
memcache_set(key, value, time, namespace, use_cache)
异步自动批处理 memcache set()
urlfetch(url, payload, method, headers, allow_truncated, follow_redirects, validate_certificate, deadline, callback)
异步自动批处理 urlfetch fetch().

事务管理方法

call_on_commit(callback)
成功提交事务时将对调用的回调加入队列。

如果不在事务中,则立即调用回调。

在事务中,可以注册多个回调;一旦事务提交,这些回调将按照其注册顺序被调用。如果事务失败,则不会调用回调。

如果回调引发异常,则异常会正常冒出。这意味着:如果立即调用回调,则回调引发的任何异常都会立即冒出。如果调用被推迟到事务提交时,则剩余的回调将被跳过,并且异常将通过 transaction() 调用冒出。(但是,事务已在此时提交。)

参数

callback
回调函数。此回调函数不采用任何参数,也不返回任何值。
in_transaction()
如果此上下文代表事务,则返回 True,否则返回 False

静态方法

default_cache_policy(key)
检查实体模型类中的 _use_cache 类变量;如果有,则返回该变量。否则返回 None
default_datastore_policy(key)
检查实体模型类中的 _use_datastore 类变量;如果有,则返回该变量。否则返回 None
default_memcache_policy(key)
检查实体模型类中的 _use_memcache 类变量;如果有,则返回该变量。否则返回 None
default_memcache_timeout_policy(key)
检查实体模型类中的 _memcache_timeout 类变量;如果有,则返回该变量。否则返回 None