Python 通过Memcache高效使用Google API特定的服务对象

Python 通过Memcache高效使用Google API特定的服务对象,python,google-app-engine,google-oauth,google-api-python-client,Python,Google App Engine,Google Oauth,Google Api Python Client,应用程序正试图在服务帐户的帮助下使用Google Apps目录API获取用户信息列表(>200个用户) if not memcache.get('directory_service'): f = file(KEY_FILE, 'r') key = f.read() f.close() credentials = SignedJwtAssertionCredentials( service_email, key, '

应用程序正试图在服务帐户的帮助下使用Google Apps目录API获取用户信息列表(>200个用户)

if not memcache.get('directory_service'):
    f = file(KEY_FILE, 'r')
    key = f.read()
    f.close()

    credentials = SignedJwtAssertionCredentials(
        service_email,
        key,
        'https://www.googleapis.com/auth/admin.directory.user',
        sub=GoogleAppAdminEmail)
    http_auth = credentials.authorize(Http())

    directory_service = build('admin', 'directory_v1', http=http_auth)
    memcache.set('directory_service', directory_service, 60 * 60 * 2)
else:
    directory_service = memcache.get('directory_service')
user = directory_service.users().get(userKey=username).execute()
我认为最好将
directory\u服务
对象保存在memcache中,以减少执行时间,这样第二个请求之后的应用程序将从memcache中获取该对象

但是在实现Memcache之后,我得到了
HttpError 401

File "C:\Users\test\appcode\oauth2client\util.py", line 135, in positional_wrapper

    return wrapped(*args, **kwargs)

File "C:\Users\test\appcode\googleapiclient\http.py", line 723, in execute

    raise HttpError(resp, content, uri=self.uri)

HttpError: <HttpError 401 when requesting https://www.googleapis.com/admin/directory/v1/users/username%40mydomain.com?alt=json returned "Login Required"> 
文件“C:\Users\test\appcode\oauth2client\util.py”,第135行,在位置包装中
已包装退货(*args,**kwargs)
文件“C:\Users\test\appcode\googleapiclient\http.py”,第723行,在execute中
raise HttpError(resp,content,uri=self.uri)
HttpError:

处理这种情况的有效方法是什么?

存储
目录\u服务
对象没有什么意义,因为它是在不调用外部API的情况下创建的

您应该存储的是
http\u auth
对象,因为生成这个对象可能需要花费很大的成本

此外,每秒只能向服务帐户请求一定次数的令牌。我不认为确切的限额在什么地方有记录,但如果您试图同时从同一服务帐户生成过多的代币,您将得到一个
超过费率限额的
错误


好的做法是将令牌存储在一些共享存储服务中。它可以是memcache或数据存储。GoogleAPI客户端附带了您应该使用的。它由数据存储支持,并使用Memcache作为可选的缓存层。

即使我保存了
http\u auth
对象,我也会遇到同样的错误。我将重复David所说的,存储auth令牌本身比试图存储执行auth流和发出请求的对象要健壮得多。对于您的使用模式(您可能实际上正在使用)来说,最坏的情况是,pickle对象中的令牌将过期,导致身份验证错误,但您的应用程序仍然认为它可以安全地抓取对象,因此无需生成新的令牌。您可能希望将令牌过期之前的时间与对象一起存储,这样可以防止问题的发生,如果确实发生了这种情况的话。