Skip to main content
 首页 » 编程设计

python之App Engine NDB 异步操作事件循环如何工作

2025年02月15日3052php

我在 App Engine 标准环境 上使用 python 运行时。

我在我的代码中使用了一些异步操作,引自教程:

  • You might be able to speed up your application by performing Datastore actions in parallel with other things, or performing a few Datastore actions in parallel with each other.

  • Tasklets are a way to write concurrent functions without threads; tasklets are executed by an event loop

https://cloud.google.com/appengine/docs/python/ndb/async

这都是关于并行执行的,但我不明白这种并行性在同步 python 代码中是如何工作的。

事件循环是如何工作的?它是否在单独的进程/线程中运行? 它执行任何真正并发的执行吗?或者它只是创建批处理 rpc 的便捷方式,它在第一次 get_result() 调用时同步运行?

https://cloud.google.com/appengine/docs/python/refdocs/modules/google/appengine/ext/ndb/eventloop

请您参考如下方法:

正如您所怀疑的那样,异步操作只是一种在阻塞第一个(以及所有后续)get_result() 调用。这适用于大多数/所有基于 RPC 的 GAE 基础设施(ndb、memcache、urlfetch 等)

如果您查看大多数调用(支持异步版本)的非异步版本的实现,您会发现它们实际上只是紧跟在 get_result()< 之后的异步版本调用 调用,例如:

  @classmethod 
  def _get_or_insert(*args, **kwds): 
    """Transactionally retrieves an existing entity or creates a new one.     
    (snip)           
    """ 
    cls, args = args[0], args[1:] 
    return cls._get_or_insert_async(*args, **kwds).get_result() 
  get_or_insert = _get_or_insert 

至于运行事件循环本身——当你的应用程序通过 get_event_loop():

def get_event_loop(): 
  """Return a EventLoop instance. 
 
  A new instance is created for each new HTTP request.  We determine 
  that we're in a new request by inspecting os.environ, which is reset 
  at the start of each request.  Also, each thread gets its own loop. 
  """ 
  ev = _state.event_loop 
  if not os.getenv(_EVENT_LOOP_KEY) and ev is not None: 
    ev.clear() 
    _state.event_loop = None 
    ev = None 
  if ev is None: 
    ev = EventLoop() 
    _state.event_loop = ev 
    os.environ[_EVENT_LOOP_KEY] = '1' 
  return ev