python - 在 Google App Engine 上处理 db.Timeout

标签 python google-app-engine

我正在测试我的应用程序(在 Google App Engine 实时服务器上)和我编写它的方式我的代码中有大约 40 个 db.GqlQuery() 语句(大部分是类的一部分)。

虽然我一直收到 db.Timeout 非常频繁

我该如何处理?我打算用这样非常残酷的代码包围我的所有查询:

  querySucceeded = False
  while not querySucceeded :
    try :
      result = db.GqlQuery( """xxx""" ).get()
      querySucceeded = True #only get here if above line doesn't raise exc
    except :
      querySucceeded = False

这样可以吗?你同意?处理 db.Timeouts 的更好方法是什么?

编辑:

我现在将它用于任何 get 查询

""" Query gets single result """
def queryGet( gql ) :
  querySucceeded = False
  while not querySucceeded :
    try :
      result = db.GqlQuery( gql ).get()
      querySucceeded = True #only get here if above line doesn't raise
    except :
      querySucceeded = False
  
  return result

我有类似的获取和计数功能。

最佳答案

这是一个重试 db.Timeout 的装饰器,改编自 Kay 框架:

import logging, time
from google.appengine.ext import db

def retry_on_timeout(retries=3, interval=1.0, exponent=2.0):
    """A decorator to retry a given function performing db operations."""
    def _decorator(func):
        def _wrapper(*args, **kwargs):
            count = 0
            while True:
                try:
                    return func(*args, **kwargs)
                except db.Timeout, e:
                    logging.debug(e)
                    if count >= retries:
                        raise e
                    else:
                        sleep_time = (exponent ** count) * interval
                        logging.warning("Retrying function %r in %d secs" %
                            (func, sleep_time))
                        time.sleep(sleep_time)
                        count += 1

        return _wrapper

    return _decorator

要使用它,只需装饰任何执行数据库操作的函数,并且你想重试:

@retry_on_timeout()
def do_the_stuff(models):
    return db.put(models)

关于python - 在 Google App Engine 上处理 db.Timeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1456070/

相关文章:

javascript - 在 Google App Engine 服务器中实现 CORS

node.js - 如何使用 NodeJs 实现 Google App 引擎冗余

python - 在 GAE 数据存储中对多个选择进行建模

python - Python 中不同嵌套字典的 Gen 填充率?

python - 从具有 'different date format"的数据框中的日期列中提取年份 - python

python - 在不同目录中以编程方式导入的文件重新加载期间未找到 ModuleSpec

python - 是否可以从 Python 运行 Falcon 应用程序?

google-app-engine - Google App Engine Go 1.11 应用程序无法访问 Google 电子表格

python - 如何正确分配给 pandas 中的多索引数据帧的切片?

python - 无法在代码中访问 UserProperty 的成员